CLI: Remove compatibility code.
[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 static const struct ast_app_stack_funcs *app_stack_callbacks;
390
391 void ast_install_stack_functions(const struct ast_app_stack_funcs *funcs)
392 {
393         app_stack_callbacks = funcs;
394 }
395
396 const char *ast_app_expand_sub_args(struct ast_channel *chan, const char *args)
397 {
398         const struct ast_app_stack_funcs *funcs;
399         const char *new_args;
400
401         funcs = app_stack_callbacks;
402         if (!funcs || !funcs->expand_sub_args) {
403                 ast_log(LOG_WARNING,
404                         "Cannot expand 'Gosub(%s)' arguments.  The app_stack module is not available.\n",
405                         args);
406                 return NULL;
407         }
408         ast_module_ref(funcs->module);
409
410         new_args = funcs->expand_sub_args(chan, args);
411         ast_module_unref(funcs->module);
412         return new_args;
413 }
414
415 int ast_app_exec_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_args, int ignore_hangup)
416 {
417         const struct ast_app_stack_funcs *funcs;
418         int res;
419
420         funcs = app_stack_callbacks;
421         if (!funcs || !funcs->run_sub) {
422                 ast_log(LOG_WARNING,
423                         "Cannot run 'Gosub(%s)'.  The app_stack module is not available.\n",
424                         sub_args);
425                 return -1;
426         }
427         ast_module_ref(funcs->module);
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 res = -1;
1031         int autoclose = 0;
1032         if (fd < 0) {
1033                 if (ast_strlen_zero(filename)) {
1034                         return -1;
1035                 }
1036                 autoclose = 1;
1037                 if (filename[0] == '/') {
1038                         ast_copy_string(tmpf, filename, sizeof(tmpf));
1039                 } else {
1040                         snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
1041                 }
1042                 if ((fd = open(tmpf, O_RDONLY)) < 0) {
1043                         ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
1044                         return -1;
1045                 }
1046         }
1047         if ((lin = ast_calloc(1, sizeof(*lin)))) {
1048                 lin->fd = fd;
1049                 lin->allowoverride = allowoverride;
1050                 lin->autoclose = autoclose;
1051                 res = ast_activate_generator(chan, &linearstream, lin);
1052         }
1053         return res;
1054 }
1055
1056 static int control_streamfile(struct ast_channel *chan,
1057         const char *file,
1058         const char *fwd,
1059         const char *rev,
1060         const char *stop,
1061         const char *suspend,
1062         const char *restart,
1063         int skipms,
1064         long *offsetms,
1065         const char *lang,
1066         ast_waitstream_fr_cb cb)
1067 {
1068         char *breaks = NULL;
1069         char *end = NULL;
1070         int blen = 2;
1071         int res;
1072         long pause_restart_point = 0;
1073         long offset = 0;
1074         struct ast_silence_generator *silgen = NULL;
1075
1076         if (!file) {
1077                 return -1;
1078         }
1079         if (offsetms) {
1080                 offset = *offsetms * 8; /* XXX Assumes 8kHz */
1081         }
1082         if (lang == NULL) {
1083                 lang = ast_channel_language(chan);
1084         }
1085
1086         if (stop) {
1087                 blen += strlen(stop);
1088         }
1089         if (suspend) {
1090                 blen += strlen(suspend);
1091         }
1092         if (restart) {
1093                 blen += strlen(restart);
1094         }
1095
1096         if (blen > 2) {
1097                 breaks = ast_alloca(blen + 1);
1098                 breaks[0] = '\0';
1099                 if (stop) {
1100                         strcat(breaks, stop);
1101                 }
1102                 if (suspend) {
1103                         strcat(breaks, suspend);
1104                 }
1105                 if (restart) {
1106                         strcat(breaks, restart);
1107                 }
1108         }
1109
1110         if ((end = strchr(file, ':'))) {
1111                 if (!strcasecmp(end, ":end")) {
1112                         *end = '\0';
1113                         end++;
1114                 } else {
1115                         end = NULL;
1116                 }
1117         }
1118
1119         for (;;) {
1120                 ast_stopstream(chan);
1121                 res = ast_streamfile(chan, file, lang);
1122                 if (!res) {
1123                         if (pause_restart_point) {
1124                                 ast_seekstream(ast_channel_stream(chan), pause_restart_point, SEEK_SET);
1125                                 pause_restart_point = 0;
1126                         }
1127                         else if (end || offset < 0) {
1128                                 if (offset == -8) {
1129                                         offset = 0;
1130                                 }
1131                                 ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
1132
1133                                 ast_seekstream(ast_channel_stream(chan), offset, SEEK_END);
1134                                 end = NULL;
1135                                 offset = 0;
1136                         } else if (offset) {
1137                                 ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
1138                                 ast_seekstream(ast_channel_stream(chan), offset, SEEK_SET);
1139                                 offset = 0;
1140                         }
1141                         if (cb) {
1142                                 res = ast_waitstream_fr_w_cb(chan, breaks, fwd, rev, skipms, cb);
1143                         } else {
1144                                 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
1145                         }
1146                 }
1147
1148                 if (res < 1) {
1149                         break;
1150                 }
1151
1152                 /* We go at next loop if we got the restart char */
1153                 if ((restart && strchr(restart, res)) || res == AST_CONTROL_STREAM_RESTART) {
1154                         ast_debug(1, "we'll restart the stream here at next loop\n");
1155                         pause_restart_point = 0;
1156                         ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1157                                 "Control: %s\r\n",
1158                                 ast_channel_name(chan),
1159                                 "Restart");
1160                         continue;
1161                 }
1162
1163                 if ((suspend && strchr(suspend, res)) || res == AST_CONTROL_STREAM_SUSPEND) {
1164                         pause_restart_point = ast_tellstream(ast_channel_stream(chan));
1165
1166                         if (ast_opt_transmit_silence) {
1167                                 silgen = ast_channel_start_silence_generator(chan);
1168                         }
1169                         ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1170                                 "Control: %s\r\n",
1171                                 ast_channel_name(chan),
1172                                 "Pause");
1173                         for (;;) {
1174                                 ast_stopstream(chan);
1175                                 if (!(res = ast_waitfordigit(chan, 1000))) {
1176                                         continue;
1177                                 } else if (res == -1 || (suspend && strchr(suspend, res)) || (stop && strchr(stop, res))
1178                                                 || res == AST_CONTROL_STREAM_SUSPEND || res == AST_CONTROL_STREAM_STOP) {
1179                                         break;
1180                                 }
1181                         }
1182                         if (silgen) {
1183                                 ast_channel_stop_silence_generator(chan, silgen);
1184                                 silgen = NULL;
1185                         }
1186
1187                         if ((suspend && (res == *suspend)) || res == AST_CONTROL_STREAM_SUSPEND) {
1188                                 res = 0;
1189                                 ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1190                                         "Control: %s\r\n",
1191                                         ast_channel_name(chan),
1192                                         "Unpause");
1193                                 continue;
1194                         }
1195                 }
1196
1197                 if (res == -1) {
1198                         break;
1199                 }
1200
1201                 /* if we get one of our stop chars, return it to the calling function */
1202                 if ((stop && strchr(stop, res)) || res == AST_CONTROL_STREAM_STOP) {
1203                         ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
1204                                 "Control: %s\r\n",
1205                                 ast_channel_name(chan),
1206                                 "Stop");
1207                         break;
1208                 }
1209         }
1210
1211         if (pause_restart_point) {
1212                 offset = pause_restart_point;
1213         } else {
1214                 if (ast_channel_stream(chan)) {
1215                         offset = ast_tellstream(ast_channel_stream(chan));
1216                 } else {
1217                         offset = -8;  /* indicate end of file */
1218                 }
1219         }
1220
1221         if (offsetms) {
1222                 *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
1223         }
1224
1225         ast_stopstream(chan);
1226
1227         return res;
1228 }
1229
1230 int ast_control_streamfile_w_cb(struct ast_channel *chan,
1231         const char *file,
1232         const char *fwd,
1233         const char *rev,
1234         const char *stop,
1235         const char *suspend,
1236         const char *restart,
1237         int skipms,
1238         long *offsetms,
1239         ast_waitstream_fr_cb cb)
1240 {
1241         return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, cb);
1242 }
1243
1244 int ast_control_streamfile(struct ast_channel *chan, const char *file,
1245                            const char *fwd, const char *rev,
1246                            const char *stop, const char *suspend,
1247                            const char *restart, int skipms, long *offsetms)
1248 {
1249         return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL, NULL);
1250 }
1251
1252 int ast_control_streamfile_lang(struct ast_channel *chan, const char *file,
1253         const char *fwd, const char *rev, const char *stop, const char *suspend,
1254         const char *restart, int skipms, const char *lang, long *offsetms)
1255 {
1256         return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, lang, NULL);
1257 }
1258
1259 enum control_tone_frame_response_result {
1260         CONTROL_TONE_RESPONSE_FAILED = -1,
1261         CONTROL_TONE_RESPONSE_NORMAL = 0,
1262         CONTROL_TONE_RESPONSE_FINISHED = 1,
1263 };
1264
1265 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)
1266 {
1267         switch (fr->subclass.integer) {
1268         case AST_CONTROL_STREAM_STOP:
1269                 ast_playtones_stop(chan);
1270                 return CONTROL_TONE_RESPONSE_FINISHED;
1271         case AST_CONTROL_STREAM_SUSPEND:
1272                 if (*paused) {
1273                         *paused = 0;
1274                         if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
1275                                 return CONTROL_TONE_RESPONSE_FAILED;
1276                         }
1277                 } else {
1278                         *paused = 1;
1279                         ast_playtones_stop(chan);
1280                 }
1281                 return CONTROL_TONE_RESPONSE_NORMAL;
1282         case AST_CONTROL_STREAM_RESTART:
1283                 ast_playtones_stop(chan);
1284                 if (ast_playtones_start(chan, 0, ts ? ts->data : tone, 0)) {
1285                         return CONTROL_TONE_RESPONSE_FAILED;
1286                 }
1287                 return CONTROL_TONE_RESPONSE_NORMAL;
1288         case AST_CONTROL_STREAM_REVERSE:
1289                 ast_log(LOG_NOTICE, "Media control operation 'reverse' not supported for media type 'tone'\n");
1290                 return CONTROL_TONE_RESPONSE_NORMAL;
1291         case AST_CONTROL_STREAM_FORWARD:
1292                 ast_log(LOG_NOTICE, "Media control operation 'forward' not supported for media type 'tone'\n");
1293                 return CONTROL_TONE_RESPONSE_NORMAL;
1294         case AST_CONTROL_HANGUP:
1295         case AST_CONTROL_BUSY:
1296         case AST_CONTROL_CONGESTION:
1297                 return CONTROL_TONE_RESPONSE_FINISHED;
1298         }
1299
1300         return CONTROL_TONE_RESPONSE_NORMAL;
1301 }
1302
1303 static int parse_tone_uri(char *tone_parser,
1304         const char **tone_indication,
1305         const char **tone_zone)
1306 {
1307         *tone_indication = strsep(&tone_parser, ";");
1308
1309         if (ast_strlen_zero(tone_parser)) {
1310                 /* Only the indication is included */
1311                 return 0;
1312         }
1313
1314         if (!(strncmp(tone_parser, "tonezone=", 9))) {
1315                 *tone_zone = tone_parser + 9;
1316         } else {
1317                 ast_log(LOG_ERROR, "Unexpected Tone URI component: %s\n", tone_parser);
1318                 return -1;
1319         }
1320
1321         return 0;
1322 }
1323
1324 int ast_control_tone(struct ast_channel *chan, const char *tone)
1325 {
1326         struct ast_tone_zone *zone = NULL;
1327         struct ast_tone_zone_sound *ts;
1328         int paused = 0;
1329         int res = 0;
1330
1331         const char *tone_indication = NULL;
1332         const char *tone_zone = NULL;
1333         char *tone_uri_parser;
1334
1335         if (ast_strlen_zero(tone)) {
1336                 return -1;
1337         }
1338
1339         tone_uri_parser = ast_strdupa(tone);
1340
1341         if (parse_tone_uri(tone_uri_parser, &tone_indication, &tone_zone)) {
1342                 return -1;
1343         }
1344
1345         if (tone_zone) {
1346                 zone = ast_get_indication_zone(tone_zone);
1347         }
1348
1349         ts = ast_get_indication_tone(zone ? zone : ast_channel_zone(chan), tone_indication);
1350
1351         if (ast_playtones_start(chan, 0, ts ? ts->data : tone_indication, 0)) {
1352                 return -1;
1353         }
1354
1355         for (;;) {
1356                 struct ast_frame *fr;
1357
1358                 if (ast_waitfor(chan, -1) < 0) {
1359                         res = -1;
1360                         break;
1361                 }
1362
1363                 fr = ast_read_noaudio(chan);
1364
1365                 if (!fr) {
1366                         res = -1;
1367                         break;
1368                 }
1369
1370                 if (fr->frametype != AST_FRAME_CONTROL) {
1371                         continue;
1372                 }
1373
1374                 res = control_tone_frame_response(chan, fr, ts, tone_indication, &paused);
1375                 if (res == CONTROL_TONE_RESPONSE_FINISHED) {
1376                         res = 0;
1377                         break;
1378                 } else if (res == CONTROL_TONE_RESPONSE_FAILED) {
1379                         res = -1;
1380                         break;
1381                 }
1382         }
1383
1384         if (ts) {
1385                 ast_tone_zone_sound_unref(ts);
1386         }
1387
1388         if (zone) {
1389                 ast_tone_zone_unref(zone);
1390         }
1391
1392         return res;
1393 }
1394
1395 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
1396 {
1397         int d = 0;
1398
1399         if ((d = ast_streamfile(chan, fn, ast_channel_language(chan)))) {
1400                 return d;
1401         }
1402
1403         d = ast_waitstream(chan, AST_DIGIT_ANY);
1404
1405         ast_stopstream(chan);
1406
1407         return d;
1408 }
1409
1410 /*!
1411  * \brief Construct a silence frame of the same duration as \a orig.
1412  *
1413  * The \a orig frame must be \ref AST_FORMAT_SLINEAR.
1414  *
1415  * \param orig Frame as basis for silence to generate.
1416  * \return New frame of silence; free with ast_frfree().
1417  * \return \c NULL on error.
1418  */
1419 static struct ast_frame *make_silence(const struct ast_frame *orig)
1420 {
1421         struct ast_frame *silence;
1422         size_t size;
1423         size_t datalen;
1424         size_t samples = 0;
1425
1426         if (!orig) {
1427                 return NULL;
1428         }
1429         do {
1430                 if (ast_format_cmp(orig->subclass.format, ast_format_slin) == AST_FORMAT_CMP_NOT_EQUAL) {
1431                         ast_log(LOG_WARNING, "Attempting to silence non-slin frame\n");
1432                         return NULL;
1433                 }
1434
1435                 samples += orig->samples;
1436
1437                 orig = AST_LIST_NEXT(orig, frame_list);
1438         } while (orig);
1439
1440         ast_verb(4, "Silencing %zu samples\n", samples);
1441
1442
1443         datalen = sizeof(short) * samples;
1444         size = sizeof(*silence) + datalen;
1445         silence = ast_calloc(1, size);
1446         if (!silence) {
1447                 return NULL;
1448         }
1449
1450         silence->mallocd = AST_MALLOCD_HDR;
1451         silence->frametype = AST_FRAME_VOICE;
1452         silence->data.ptr = (void *)(silence + 1);
1453         silence->samples = samples;
1454         silence->datalen = datalen;
1455
1456         silence->subclass.format = ao2_bump(ast_format_slin);
1457
1458         return silence;
1459 }
1460
1461 /*!
1462  * \brief Sets a channel's read format to \ref AST_FORMAT_SLINEAR, recording
1463  * its original format.
1464  *
1465  * \param chan Channel to modify.
1466  * \param[out] orig_format Output variable to store channel's original read
1467  *                         format.
1468  * \return 0 on success.
1469  * \return -1 on error.
1470  */
1471 static int set_read_to_slin(struct ast_channel *chan, struct ast_format **orig_format)
1472 {
1473         if (!chan || !orig_format) {
1474                 return -1;
1475         }
1476         *orig_format = ao2_bump(ast_channel_readformat(chan));
1477         return ast_set_read_format(chan, ast_format_slin);
1478 }
1479
1480 static int global_silence_threshold = 128;
1481 static int global_maxsilence = 0;
1482
1483 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
1484  * \param chan Channel to playback to/record from.
1485  * \param playfile Filename of sound to play before recording begins.
1486  * \param recordfile Filename to record to.
1487  * \param maxtime Maximum length of recording (in seconds).
1488  * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
1489  * \param duration Where to store actual length of the recorded message (in milliseconds).
1490  * \param sound_duration Where to store the length of the recorded message (in milliseconds), minus any silence
1491  * \param beep Whether to play a beep before starting to record.
1492  * \param silencethreshold
1493  * \param maxsilence Length of silence that will end a recording (in milliseconds).
1494  * \param path Optional filesystem path to unlock.
1495  * \param prepend If true, prepend the recorded audio to an existing file and follow prepend mode recording rules
1496  * \param acceptdtmf DTMF digits that will end the recording.
1497  * \param canceldtmf DTMF digits that will cancel the recording.
1498  * \param skip_confirmation_sound If true, don't play auth-thankyou at end. Nice for custom recording prompts in apps.
1499  *
1500  * \retval -1 failure or hangup
1501  * \retval 'S' Recording ended from silence timeout
1502  * \retval 't' Recording ended from the message exceeding the maximum duration, or via DTMF in prepend mode
1503  * \retval dtmfchar Recording ended via the return value's DTMF character for either cancel or accept.
1504  */
1505 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)
1506 {
1507         int d = 0;
1508         char *fmts;
1509         char comment[256];
1510         int x, fmtcnt = 1, res = -1, outmsg = 0;
1511         struct ast_filestream *others[AST_MAX_FORMATS];
1512         char *sfmt[AST_MAX_FORMATS];
1513         char *stringp = NULL;
1514         time_t start, end;
1515         struct ast_dsp *sildet = NULL;   /* silence detector dsp */
1516         int totalsilence = 0;
1517         int dspsilence = 0;
1518         int olddspsilence = 0;
1519         struct ast_format *rfmt = NULL;
1520         struct ast_silence_generator *silgen = NULL;
1521         char prependfile[PATH_MAX];
1522         int ioflags;    /* IO flags for writing output file */
1523
1524         ioflags = O_CREAT|O_WRONLY;
1525
1526         switch (if_exists) {
1527         case AST_RECORD_IF_EXISTS_FAIL:
1528                 ioflags |= O_EXCL;
1529                 break;
1530         case AST_RECORD_IF_EXISTS_OVERWRITE:
1531                 ioflags |= O_TRUNC;
1532                 break;
1533         case AST_RECORD_IF_EXISTS_APPEND:
1534                 ioflags |= O_APPEND;
1535                 break;
1536         case AST_RECORD_IF_EXISTS_ERROR:
1537                 ast_assert(0);
1538                 break;
1539         }
1540
1541         if (silencethreshold < 0) {
1542                 silencethreshold = global_silence_threshold;
1543         }
1544
1545         if (maxsilence < 0) {
1546                 maxsilence = global_maxsilence;
1547         }
1548
1549         /* barf if no pointer passed to store duration in */
1550         if (!duration) {
1551                 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
1552                 return -1;
1553         }
1554
1555         ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
1556         snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, ast_channel_name(chan));
1557
1558         if (playfile || beep) {
1559                 if (!beep) {
1560                         d = ast_play_and_wait(chan, playfile);
1561                 }
1562                 if (d > -1) {
1563                         d = ast_stream_and_wait(chan, "beep", "");
1564                 }
1565                 if (d < 0) {
1566                         return -1;
1567                 }
1568         }
1569
1570         if (prepend) {
1571                 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
1572                 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
1573         }
1574
1575         fmts = ast_strdupa(fmt);
1576
1577         stringp = fmts;
1578         strsep(&stringp, "|");
1579         ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
1580         sfmt[0] = ast_strdupa(fmts);
1581
1582         while ((fmt = strsep(&stringp, "|"))) {
1583                 if (fmtcnt > AST_MAX_FORMATS - 1) {
1584                         ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
1585                         break;
1586                 }
1587                 sfmt[fmtcnt++] = ast_strdupa(fmt);
1588         }
1589
1590         end = start = time(NULL);  /* pre-initialize end to be same as start in case we never get into loop */
1591         for (x = 0; x < fmtcnt; x++) {
1592                 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, ioflags, 0, AST_FILE_MODE);
1593                 ast_verb(3, "x=%d, open writing:  %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
1594
1595                 if (!others[x]) {
1596                         break;
1597                 }
1598         }
1599
1600         if (path) {
1601                 ast_unlock_path(path);
1602         }
1603
1604         if (maxsilence > 0) {
1605                 sildet = ast_dsp_new(); /* Create the silence detector */
1606                 if (!sildet) {
1607                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
1608                         return -1;
1609                 }
1610                 ast_dsp_set_threshold(sildet, silencethreshold);
1611                 res = set_read_to_slin(chan, &rfmt);
1612                 if (res < 0) {
1613                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
1614                         ast_dsp_free(sildet);
1615                         ao2_cleanup(rfmt);
1616                         return -1;
1617                 }
1618         }
1619
1620         if (!prepend) {
1621                 /* Request a video update */
1622                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
1623
1624                 if (ast_opt_transmit_silence) {
1625                         silgen = ast_channel_start_silence_generator(chan);
1626                 }
1627         }
1628
1629         if (x == fmtcnt) {
1630                 /* Loop, writing the packets we read to the writer(s), until
1631                  * we have reason to stop. */
1632                 struct ast_frame *f;
1633                 int paused = 0;
1634                 int muted = 0;
1635                 time_t pause_start = 0;
1636                 int paused_secs = 0;
1637                 int pausedsilence = 0;
1638
1639                 for (;;) {
1640                         if (!(res = ast_waitfor(chan, 2000))) {
1641                                 ast_debug(1, "One waitfor failed, trying another\n");
1642                                 /* Try one more time in case of masq */
1643                                 if (!(res = ast_waitfor(chan, 2000))) {
1644                                         ast_log(LOG_WARNING, "No audio available on %s??\n", ast_channel_name(chan));
1645                                         res = -1;
1646                                 }
1647                         }
1648
1649                         if (res < 0) {
1650                                 f = NULL;
1651                                 break;
1652                         }
1653                         if (!(f = ast_read(chan))) {
1654                                 break;
1655                         }
1656                         if (f->frametype == AST_FRAME_VOICE) {
1657                                 /* write each format */
1658                                 if (paused) {
1659                                         /* It's all good */
1660                                         res = 0;
1661                                 } else {
1662                                         struct ast_frame *silence = NULL;
1663                                         struct ast_frame *orig = f;
1664
1665                                         if (muted) {
1666                                                 silence = make_silence(orig);
1667                                                 if (!silence) {
1668                                                         ast_log(LOG_WARNING, "Error creating silence\n");
1669                                                         break;
1670                                                 }
1671                                                 f = silence;
1672                                         }
1673                                         for (x = 0; x < fmtcnt; x++) {
1674                                                 if (prepend && !others[x]) {
1675                                                         break;
1676                                                 }
1677                                                 res = ast_writestream(others[x], f);
1678                                         }
1679                                         ast_frame_dtor(silence);
1680                                         f = orig;
1681                                 }
1682
1683                                 /* Silence Detection */
1684                                 if (maxsilence > 0) {
1685                                         dspsilence = 0;
1686                                         ast_dsp_silence(sildet, f, &dspsilence);
1687                                         if (olddspsilence > dspsilence) {
1688                                                 totalsilence += olddspsilence;
1689                                         }
1690                                         olddspsilence = dspsilence;
1691
1692                                         if (paused) {
1693                                                 /* record how much silence there was while we are paused */
1694                                                 pausedsilence = dspsilence;
1695                                         } else if (dspsilence > pausedsilence) {
1696                                                 /* ignore the paused silence */
1697                                                 dspsilence -= pausedsilence;
1698                                         } else {
1699                                                 /* dspsilence has reset, reset pausedsilence */
1700                                                 pausedsilence = 0;
1701                                         }
1702
1703                                         if (dspsilence > maxsilence) {
1704                                                 /* Ended happily with silence */
1705                                                 ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
1706                                                 res = 'S';
1707                                                 outmsg = 2;
1708                                                 break;
1709                                         }
1710                                 }
1711                                 /* Exit on any error */
1712                                 if (res) {
1713                                         ast_log(LOG_WARNING, "Error writing frame\n");
1714                                         break;
1715                                 }
1716                         } else if (f->frametype == AST_FRAME_VIDEO) {
1717                                 /* Write only once */
1718                                 ast_writestream(others[0], f);
1719                         } else if (f->frametype == AST_FRAME_DTMF) {
1720                                 if (prepend) {
1721                                 /* stop recording with any digit */
1722                                         ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1723                                         res = 't';
1724                                         outmsg = 2;
1725                                         break;
1726                                 }
1727                                 if (strchr(acceptdtmf, f->subclass.integer)) {
1728                                         ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1729                                         res = f->subclass.integer;
1730                                         outmsg = 2;
1731                                         break;
1732                                 }
1733                                 if (strchr(canceldtmf, f->subclass.integer)) {
1734                                         ast_verb(3, "User canceled message by pressing %c\n", f->subclass.integer);
1735                                         res = f->subclass.integer;
1736                                         outmsg = 0;
1737                                         break;
1738                                 }
1739                         } else if (f->frametype == AST_FRAME_CONTROL) {
1740                                 if (f->subclass.integer == AST_CONTROL_RECORD_CANCEL) {
1741                                         ast_verb(3, "Message canceled by control\n");
1742                                         outmsg = 0; /* cancels the recording */
1743                                         res = 0;
1744                                         break;
1745                                 } else if (f->subclass.integer == AST_CONTROL_RECORD_STOP) {
1746                                         ast_verb(3, "Message ended by control\n");
1747                                         res = 0;
1748                                         break;
1749                                 } else if (f->subclass.integer == AST_CONTROL_RECORD_SUSPEND) {
1750                                         paused = !paused;
1751                                         ast_verb(3, "Message %spaused by control\n",
1752                                                 paused ? "" : "un");
1753                                         if (paused) {
1754                                                 pause_start = time(NULL);
1755                                         } else {
1756                                                 paused_secs += time(NULL) - pause_start;
1757                                         }
1758                                 } else if (f->subclass.integer == AST_CONTROL_RECORD_MUTE) {
1759                                         muted = !muted;
1760                                         ast_verb(3, "Message %smuted by control\n",
1761                                                 muted ? "" : "un");
1762                                         /* We can only silence slin frames, so
1763                                          * set the mode, if we haven't already
1764                                          * for sildet
1765                                          */
1766                                         if (muted && !rfmt) {
1767                                                 ast_verb(3, "Setting read format to linear mode\n");
1768                                                 res = set_read_to_slin(chan, &rfmt);
1769                                                 if (res < 0) {
1770                                                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
1771                                                         break;
1772                                                 }
1773                                         }
1774                                 }
1775                         }
1776                         if (maxtime && !paused) {
1777                                 end = time(NULL);
1778                                 if (maxtime < (end - start - paused_secs)) {
1779                                         ast_verb(3, "Took too long, cutting it short...\n");
1780                                         res = 't';
1781                                         outmsg = 2;
1782                                         break;
1783                                 }
1784                         }
1785                         ast_frfree(f);
1786                 }
1787                 if (!f) {
1788                         ast_verb(3, "User hung up\n");
1789                         res = -1;
1790                         outmsg = 1;
1791                 } else {
1792                         ast_frfree(f);
1793                 }
1794         } else {
1795                 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
1796         }
1797
1798         if (!prepend) {
1799                 if (silgen) {
1800                         ast_channel_stop_silence_generator(chan, silgen);
1801                 }
1802         }
1803
1804         /*!\note
1805          * Instead of asking how much time passed (end - start), calculate the number
1806          * of seconds of audio which actually went into the file.  This fixes a
1807          * problem where audio is stopped up on the network and never gets to us.
1808          *
1809          * Note that we still want to use the number of seconds passed for the max
1810          * message, otherwise we could get a situation where this stream is never
1811          * closed (which would create a resource leak).
1812          */
1813         *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
1814         if (sound_duration) {
1815                 *sound_duration = *duration;
1816         }
1817
1818         if (!prepend) {
1819                 /* Reduce duration by a total silence amount */
1820                 if (olddspsilence <= dspsilence) {
1821                         totalsilence += dspsilence;
1822                 }
1823
1824                 if (sound_duration) {
1825                         if (totalsilence > 0) {
1826                                 *sound_duration -= (totalsilence - 200) / 1000;
1827                         }
1828                         if (*sound_duration < 0) {
1829                                 *sound_duration = 0;
1830                         }
1831                 }
1832
1833                 if (dspsilence > 0) {
1834                         *duration -= (dspsilence - 200) / 1000;
1835                 }
1836
1837                 if (*duration < 0) {
1838                         *duration = 0;
1839                 }
1840
1841                 for (x = 0; x < fmtcnt; x++) {
1842                         if (!others[x]) {
1843                                 break;
1844                         }
1845                         /*!\note
1846                          * If we ended with silence, trim all but the first 200ms of silence
1847                          * off the recording.  However, if we ended with '#', we don't want
1848                          * to trim ANY part of the recording.
1849                          */
1850                         if (res > 0 && dspsilence) {
1851                                 /* rewind only the trailing silence */
1852                                 ast_stream_rewind(others[x], dspsilence - 200);
1853                         }
1854                         ast_truncstream(others[x]);
1855                         ast_closestream(others[x]);
1856                 }
1857         } else if (prepend && outmsg) {
1858                 struct ast_filestream *realfiles[AST_MAX_FORMATS];
1859                 struct ast_frame *fr;
1860
1861                 for (x = 0; x < fmtcnt; x++) {
1862                         snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
1863                         realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
1864                         if (!others[x]) {
1865                                 break;
1866                         }
1867                         if (!realfiles[x]) {
1868                                 ast_closestream(others[x]);
1869                                 continue;
1870                         }
1871                         /*!\note Same logic as above. */
1872                         if (dspsilence) {
1873                                 ast_stream_rewind(others[x], dspsilence - 200);
1874                         }
1875                         ast_truncstream(others[x]);
1876                         /* add the original file too */
1877                         while ((fr = ast_readframe(realfiles[x]))) {
1878                                 ast_writestream(others[x], fr);
1879                                 ast_frfree(fr);
1880                         }
1881                         ast_closestream(others[x]);
1882                         ast_closestream(realfiles[x]);
1883                         ast_filerename(prependfile, recordfile, sfmt[x]);
1884                         ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
1885                         ast_filedelete(prependfile, sfmt[x]);
1886                 }
1887         } else {
1888                 for (x = 0; x < fmtcnt; x++) {
1889                         if (!others[x]) {
1890                                 break;
1891                         }
1892                         ast_closestream(others[x]);
1893                 }
1894         }
1895
1896         if (rfmt && ast_set_read_format(chan, rfmt)) {
1897                 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_format_get_name(rfmt), ast_channel_name(chan));
1898         }
1899         ao2_cleanup(rfmt);
1900         if ((outmsg == 2) && (!skip_confirmation_sound)) {
1901                 ast_stream_and_wait(chan, "auth-thankyou", "");
1902         }
1903         if (sildet) {
1904                 ast_dsp_free(sildet);
1905         }
1906         return res;
1907 }
1908
1909 static const char default_acceptdtmf[] = "#";
1910 static const char default_canceldtmf[] = "";
1911
1912 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)
1913 {
1914         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);
1915 }
1916
1917 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)
1918 {
1919         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);
1920 }
1921
1922 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)
1923 {
1924         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);
1925 }
1926
1927 /* Channel group core functions */
1928
1929 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
1930 {
1931         int res = 0;
1932         char tmp[256];
1933         char *grp = NULL, *cat = NULL;
1934
1935         if (!ast_strlen_zero(data)) {
1936                 ast_copy_string(tmp, data, sizeof(tmp));
1937                 grp = tmp;
1938                 if ((cat = strchr(tmp, '@'))) {
1939                         *cat++ = '\0';
1940                 }
1941         }
1942
1943         if (!ast_strlen_zero(grp)) {
1944                 ast_copy_string(group, grp, group_max);
1945         } else {
1946                 *group = '\0';
1947         }
1948
1949         if (!ast_strlen_zero(cat)) {
1950                 ast_copy_string(category, cat, category_max);
1951         }
1952
1953         return res;
1954 }
1955
1956 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
1957 {
1958         int res = 0;
1959         char group[80] = "", category[80] = "";
1960         struct ast_group_info *gi = NULL;
1961         size_t len = 0;
1962
1963         if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
1964                 return -1;
1965         }
1966
1967         /* Calculate memory we will need if this is new */
1968         len = sizeof(*gi) + strlen(group) + 1;
1969         if (!ast_strlen_zero(category)) {
1970                 len += strlen(category) + 1;
1971         }
1972
1973         AST_RWLIST_WRLOCK(&groups);
1974         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1975                 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1976                         AST_RWLIST_REMOVE_CURRENT(group_list);
1977                         ast_free(gi);
1978                         break;
1979                 }
1980         }
1981         AST_RWLIST_TRAVERSE_SAFE_END;
1982
1983         if (ast_strlen_zero(group)) {
1984                 /* Enable unsetting the group */
1985         } else if ((gi = ast_calloc(1, len))) {
1986                 gi->chan = chan;
1987                 gi->group = (char *) gi + sizeof(*gi);
1988                 strcpy(gi->group, group);
1989                 if (!ast_strlen_zero(category)) {
1990                         gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
1991                         strcpy(gi->category, category);
1992                 }
1993                 AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
1994         } else {
1995                 res = -1;
1996         }
1997
1998         AST_RWLIST_UNLOCK(&groups);
1999
2000         return res;
2001 }
2002
2003 int ast_app_group_get_count(const char *group, const char *category)
2004 {
2005         struct ast_group_info *gi = NULL;
2006         int count = 0;
2007
2008         if (ast_strlen_zero(group)) {
2009                 return 0;
2010         }
2011
2012         AST_RWLIST_RDLOCK(&groups);
2013         AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
2014                 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
2015                         count++;
2016                 }
2017         }
2018         AST_RWLIST_UNLOCK(&groups);
2019
2020         return count;
2021 }
2022
2023 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
2024 {
2025         struct ast_group_info *gi = NULL;
2026         regex_t regexbuf_group;
2027         regex_t regexbuf_category;
2028         int count = 0;
2029
2030         if (ast_strlen_zero(groupmatch)) {
2031                 ast_log(LOG_NOTICE, "groupmatch empty\n");
2032                 return 0;
2033         }
2034
2035         /* if regex compilation fails, return zero matches */
2036         if (regcomp(&regexbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
2037                 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
2038                 return 0;
2039         }
2040
2041         if (!ast_strlen_zero(category) && regcomp(&regexbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
2042                 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
2043                 regfree(&regexbuf_group);
2044                 return 0;
2045         }
2046
2047         AST_RWLIST_RDLOCK(&groups);
2048         AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
2049                 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)))) {
2050                         count++;
2051                 }
2052         }
2053         AST_RWLIST_UNLOCK(&groups);
2054
2055         regfree(&regexbuf_group);
2056         if (!ast_strlen_zero(category)) {
2057                 regfree(&regexbuf_category);
2058         }
2059
2060         return count;
2061 }
2062
2063 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
2064 {
2065         struct ast_group_info *gi = NULL;
2066
2067         AST_RWLIST_WRLOCK(&groups);
2068         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
2069                 if (gi->chan == old) {
2070                         gi->chan = new;
2071                 } else if (gi->chan == new) {
2072                         AST_RWLIST_REMOVE_CURRENT(group_list);
2073                         ast_free(gi);
2074                 }
2075         }
2076         AST_RWLIST_TRAVERSE_SAFE_END;
2077         AST_RWLIST_UNLOCK(&groups);
2078
2079         return 0;
2080 }
2081
2082 int ast_app_group_discard(struct ast_channel *chan)
2083 {
2084         struct ast_group_info *gi = NULL;
2085
2086         AST_RWLIST_WRLOCK(&groups);
2087         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
2088                 if (gi->chan == chan) {
2089                         AST_RWLIST_REMOVE_CURRENT(group_list);
2090                         ast_free(gi);
2091                 }
2092         }
2093         AST_RWLIST_TRAVERSE_SAFE_END;
2094         AST_RWLIST_UNLOCK(&groups);
2095
2096         return 0;
2097 }
2098
2099 int ast_app_group_list_wrlock(void)
2100 {
2101         return AST_RWLIST_WRLOCK(&groups);
2102 }
2103
2104 int ast_app_group_list_rdlock(void)
2105 {
2106         return AST_RWLIST_RDLOCK(&groups);
2107 }
2108
2109 struct ast_group_info *ast_app_group_list_head(void)
2110 {
2111         return AST_RWLIST_FIRST(&groups);
2112 }
2113
2114 int ast_app_group_list_unlock(void)
2115 {
2116         return AST_RWLIST_UNLOCK(&groups);
2117 }
2118
2119 unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
2120 {
2121         int argc;
2122         char *scan, *wasdelim = NULL;
2123         int paren = 0, quote = 0, bracket = 0;
2124
2125         if (!array || !arraylen) {
2126                 return 0;
2127         }
2128
2129         memset(array, 0, arraylen * sizeof(*array));
2130
2131         if (!buf) {
2132                 return 0;
2133         }
2134
2135         scan = buf;
2136
2137         for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
2138                 array[argc] = scan;
2139                 for (; *scan; scan++) {
2140                         if (*scan == '(') {
2141                                 paren++;
2142                         } else if (*scan == ')') {
2143                                 if (paren) {
2144                                         paren--;
2145                                 }
2146                         } else if (*scan == '[') {
2147                                 bracket++;
2148                         } else if (*scan == ']') {
2149                                 if (bracket) {
2150                                         bracket--;
2151                                 }
2152                         } else if (*scan == '"' && delim != '"') {
2153                                 quote = quote ? 0 : 1;
2154                                 if (remove_chars) {
2155                                         /* Remove quote character from argument */
2156                                         memmove(scan, scan + 1, strlen(scan));
2157                                         scan--;
2158                                 }
2159                         } else if (*scan == '\\') {
2160                                 if (remove_chars) {
2161                                         /* Literal character, don't parse */
2162                                         memmove(scan, scan + 1, strlen(scan));
2163                                 } else {
2164                                         scan++;
2165                                 }
2166                         } else if ((*scan == delim) && !paren && !quote && !bracket) {
2167                                 wasdelim = scan;
2168                                 *scan++ = '\0';
2169                                 break;
2170                         }
2171                 }
2172         }
2173
2174         /* If the last character in the original string was the delimiter, then
2175          * there is one additional argument. */
2176         if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
2177                 array[argc++] = scan;
2178         }
2179
2180         return argc;
2181 }
2182
2183 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
2184 {
2185         char *s;
2186         char *fs;
2187         int res;
2188         int fd;
2189         int lp = strlen(path);
2190         time_t start;
2191
2192         s = ast_alloca(lp + 10);
2193         fs = ast_alloca(lp + 20);
2194
2195         snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, (unsigned long)ast_random());
2196         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
2197         if (fd < 0) {
2198                 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
2199                 return AST_LOCK_PATH_NOT_FOUND;
2200         }
2201         close(fd);
2202
2203         snprintf(s, strlen(path) + 9, "%s/.lock", path);
2204         start = time(NULL);
2205         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
2206                 sched_yield();
2207         }
2208
2209         unlink(fs);
2210
2211         if (res) {
2212                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
2213                 return AST_LOCK_TIMEOUT;
2214         } else {
2215                 ast_debug(1, "Locked path '%s'\n", path);
2216                 return AST_LOCK_SUCCESS;
2217         }
2218 }
2219
2220 static int ast_unlock_path_lockfile(const char *path)
2221 {
2222         char *s;
2223         int res;
2224
2225         s = ast_alloca(strlen(path) + 10);
2226
2227         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
2228
2229         if ((res = unlink(s))) {
2230                 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
2231         } else {
2232                 ast_debug(1, "Unlocked path '%s'\n", path);
2233         }
2234
2235         return res;
2236 }
2237
2238 struct path_lock {
2239         AST_LIST_ENTRY(path_lock) le;
2240         int fd;
2241         char *path;
2242 };
2243
2244 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
2245
2246 static void path_lock_destroy(struct path_lock *obj)
2247 {
2248         if (obj->fd >= 0) {
2249                 close(obj->fd);
2250         }
2251         if (obj->path) {
2252                 ast_free(obj->path);
2253         }
2254         ast_free(obj);
2255 }
2256
2257 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
2258 {
2259         char *fs;
2260         int res;
2261         int fd;
2262         time_t start;
2263         struct path_lock *pl;
2264         struct stat st, ost;
2265
2266         fs = ast_alloca(strlen(path) + 20);
2267
2268         snprintf(fs, strlen(path) + 19, "%s/lock", path);
2269         if (lstat(fs, &st) == 0) {
2270                 if ((st.st_mode & S_IFMT) == S_IFLNK) {
2271                         ast_log(LOG_WARNING, "Unable to create lock file "
2272                                         "'%s': it's already a symbolic link\n",
2273                                         fs);
2274                         return AST_LOCK_FAILURE;
2275                 }
2276                 if (st.st_nlink > 1) {
2277                         ast_log(LOG_WARNING, "Unable to create lock file "
2278                                         "'%s': %u hard links exist\n",
2279                                         fs, (unsigned int) st.st_nlink);
2280                         return AST_LOCK_FAILURE;
2281                 }
2282         }
2283         if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
2284                 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
2285                                 fs, strerror(errno));
2286                 return AST_LOCK_PATH_NOT_FOUND;
2287         }
2288         if (!(pl = ast_calloc(1, sizeof(*pl)))) {
2289                 /* We don't unlink the lock file here, on the possibility that
2290                  * someone else created it - better to leave a little mess
2291                  * than create a big one by destroying someone else's lock
2292                  * and causing something to be corrupted.
2293                  */
2294                 close(fd);
2295                 return AST_LOCK_FAILURE;
2296         }
2297         pl->fd = fd;
2298         pl->path = ast_strdup(path);
2299
2300         time(&start);
2301         while (
2302                 #ifdef SOLARIS
2303                 ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
2304                 #else
2305                 ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
2306                 #endif
2307                         (errno == EWOULDBLOCK) &&
2308                         (time(NULL) - start < 5))
2309                 usleep(1000);
2310         if (res) {
2311                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
2312                                 path, strerror(errno));
2313                 /* No unlinking of lock done, since we tried and failed to
2314                  * flock() it.
2315                  */
2316                 path_lock_destroy(pl);
2317                 return AST_LOCK_TIMEOUT;
2318         }
2319
2320         /* Check for the race where the file is recreated or deleted out from
2321          * underneath us.
2322          */
2323         if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
2324                         st.st_dev != ost.st_dev &&
2325                         st.st_ino != ost.st_ino) {
2326                 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
2327                                 "file changed underneath us\n", fs);
2328                 path_lock_destroy(pl);
2329                 return AST_LOCK_FAILURE;
2330         }
2331
2332         /* Success: file created, flocked, and is the one we started with */
2333         AST_LIST_LOCK(&path_lock_list);
2334         AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
2335         AST_LIST_UNLOCK(&path_lock_list);
2336
2337         ast_debug(1, "Locked path '%s'\n", path);
2338
2339         return AST_LOCK_SUCCESS;
2340 }
2341
2342 static int ast_unlock_path_flock(const char *path)
2343 {
2344         char *s;
2345         struct path_lock *p;
2346
2347         s = ast_alloca(strlen(path) + 20);
2348
2349         AST_LIST_LOCK(&path_lock_list);
2350         AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
2351                 if (!strcmp(p->path, path)) {
2352                         AST_LIST_REMOVE_CURRENT(le);
2353                         break;
2354                 }
2355         }
2356         AST_LIST_TRAVERSE_SAFE_END;
2357         AST_LIST_UNLOCK(&path_lock_list);
2358
2359         if (p) {
2360                 snprintf(s, strlen(path) + 19, "%s/lock", path);
2361                 unlink(s);
2362                 path_lock_destroy(p);
2363                 ast_debug(1, "Unlocked path '%s'\n", path);
2364         } else {
2365                 ast_debug(1, "Failed to unlock path '%s': "
2366                                 "lock not found\n", path);
2367         }
2368
2369         return 0;
2370 }
2371
2372 void ast_set_lock_type(enum AST_LOCK_TYPE type)
2373 {
2374         ast_lock_type = type;
2375 }
2376
2377 enum AST_LOCK_RESULT ast_lock_path(const char *path)
2378 {
2379         enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
2380
2381         switch (ast_lock_type) {
2382         case AST_LOCK_TYPE_LOCKFILE:
2383                 r = ast_lock_path_lockfile(path);
2384                 break;
2385         case AST_LOCK_TYPE_FLOCK:
2386                 r = ast_lock_path_flock(path);
2387                 break;
2388         }
2389
2390         return r;
2391 }
2392
2393 int ast_unlock_path(const char *path)
2394 {
2395         int r = 0;
2396
2397         switch (ast_lock_type) {
2398         case AST_LOCK_TYPE_LOCKFILE:
2399                 r = ast_unlock_path_lockfile(path);
2400                 break;
2401         case AST_LOCK_TYPE_FLOCK:
2402                 r = ast_unlock_path_flock(path);
2403                 break;
2404         }
2405
2406         return r;
2407 }
2408
2409 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
2410 {
2411         int silencethreshold;
2412         int maxsilence = 0;
2413         int res = 0;
2414         int cmd = 0;
2415         int max_attempts = 3;
2416         int attempts = 0;
2417         int recorded = 0;
2418         int message_exists = 0;
2419         /* Note that urgent and private are for flagging messages as such in the future */
2420
2421         /* barf if no pointer passed to store duration in */
2422         if (!duration) {
2423                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
2424                 return -1;
2425         }
2426
2427         cmd = '3';       /* Want to start by recording */
2428
2429         silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
2430
2431         while ((cmd >= 0) && (cmd != 't')) {
2432                 switch (cmd) {
2433                 case '1':
2434                         if (!message_exists) {
2435                                 /* In this case, 1 is to record a message */
2436                                 cmd = '3';
2437                                 break;
2438                         } else {
2439                                 ast_stream_and_wait(chan, "vm-msgsaved", "");
2440                                 cmd = 't';
2441                                 return res;
2442                         }
2443                 case '2':
2444                         /* Review */
2445                         ast_verb(3, "Reviewing the recording\n");
2446                         cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
2447                         break;
2448                 case '3':
2449                         message_exists = 0;
2450                         /* Record */
2451                         ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
2452                         recorded = 1;
2453                         if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
2454                                 /* User has hung up, no options to give */
2455                                 return cmd;
2456                         }
2457                         if (cmd == '0') {
2458                                 break;
2459                         } else if (cmd == '*') {
2460                                 break;
2461                         } else {
2462                                 /* If all is well, a message exists */
2463                                 message_exists = 1;
2464                                 cmd = 0;
2465                         }
2466                         break;
2467                 case '4':
2468                 case '5':
2469                 case '6':
2470                 case '7':
2471                 case '8':
2472                 case '9':
2473                 case '*':
2474                 case '#':
2475                         cmd = ast_play_and_wait(chan, "vm-sorry");
2476                         break;
2477                 default:
2478                         if (message_exists) {
2479                                 cmd = ast_play_and_wait(chan, "vm-review");
2480                         } else {
2481                                 if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
2482                                         cmd = ast_waitfordigit(chan, 600);
2483                                 }
2484                         }
2485
2486                         if (!cmd) {
2487                                 cmd = ast_waitfordigit(chan, 6000);
2488                         }
2489                         if (!cmd) {
2490                                 attempts++;
2491                         }
2492                         if (attempts > max_attempts) {
2493                                 cmd = 't';
2494                         }
2495                 }
2496         }
2497         if (cmd == 't') {
2498                 cmd = 0;
2499         }
2500         return cmd;
2501 }
2502
2503 #define RES_UPONE (1 << 16)
2504 #define RES_EXIT  (1 << 17)
2505 #define RES_REPEAT (1 << 18)
2506 #define RES_RESTART ((1 << 19) | RES_REPEAT)
2507
2508 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
2509
2510 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
2511 {
2512         int res;
2513         int (*ivr_func)(struct ast_channel *, void *);
2514         char *c;
2515         char *n;
2516
2517         switch (option->action) {
2518         case AST_ACTION_UPONE:
2519                 return RES_UPONE;
2520         case AST_ACTION_EXIT:
2521                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
2522         case AST_ACTION_REPEAT:
2523                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
2524         case AST_ACTION_RESTART:
2525                 return RES_RESTART ;
2526         case AST_ACTION_NOOP:
2527                 return 0;
2528         case AST_ACTION_BACKGROUND:
2529                 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
2530                 if (res < 0) {
2531                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2532                         res = 0;
2533                 }
2534                 return res;
2535         case AST_ACTION_PLAYBACK:
2536                 res = ast_stream_and_wait(chan, (char *)option->adata, "");
2537                 if (res < 0) {
2538                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2539                         res = 0;
2540                 }
2541                 return res;
2542         case AST_ACTION_MENU:
2543                 if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
2544                         /* Do not pass entry errors back up, treat as though it was an "UPONE" */
2545                         res = 0;
2546                 }
2547                 return res;
2548         case AST_ACTION_WAITOPTION:
2549                 if (!(res = ast_waitfordigit(chan, ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000))) {
2550                         return 't';
2551                 }
2552                 return res;
2553         case AST_ACTION_CALLBACK:
2554                 ivr_func = option->adata;
2555                 res = ivr_func(chan, cbdata);
2556                 return res;
2557         case AST_ACTION_TRANSFER:
2558                 res = ast_parseable_goto(chan, option->adata);
2559                 return 0;
2560         case AST_ACTION_PLAYLIST:
2561         case AST_ACTION_BACKLIST:
2562                 res = 0;
2563                 c = ast_strdupa(option->adata);
2564                 while ((n = strsep(&c, ";"))) {
2565                         if ((res = ast_stream_and_wait(chan, n,
2566                                         (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
2567                                 break;
2568                         }
2569                 }
2570                 ast_stopstream(chan);
2571                 return res;
2572         default:
2573                 ast_log(LOG_NOTICE, "Unknown dispatch function %u, ignoring!\n", option->action);
2574                 return 0;
2575         }
2576         return -1;
2577 }
2578
2579 static int option_exists(struct ast_ivr_menu *menu, char *option)
2580 {
2581         int x;
2582         for (x = 0; menu->options[x].option; x++) {
2583                 if (!strcasecmp(menu->options[x].option, option)) {
2584                         return x;
2585                 }
2586         }
2587         return -1;
2588 }
2589
2590 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
2591 {
2592         int x;
2593         for (x = 0; menu->options[x].option; x++) {
2594                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
2595                                 (menu->options[x].option[strlen(option)])) {
2596                         return x;
2597                 }
2598         }
2599         return -1;
2600 }
2601
2602 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
2603 {
2604         int res = 0;
2605         int ms;
2606         while (option_matchmore(menu, exten)) {
2607                 ms = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
2608                 if (strlen(exten) >= maxexten - 1) {
2609                         break;
2610                 }
2611                 if ((res = ast_waitfordigit(chan, ms)) < 1) {
2612                         break;
2613                 }
2614                 exten[strlen(exten) + 1] = '\0';
2615                 exten[strlen(exten)] = res;
2616         }
2617         return res > 0 ? 0 : res;
2618 }
2619
2620 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2621 {
2622         /* Execute an IVR menu structure */
2623         int res = 0;
2624         int pos = 0;
2625         int retries = 0;
2626         char exten[AST_MAX_EXTENSION] = "s";
2627         if (option_exists(menu, "s") < 0) {
2628                 strcpy(exten, "g");
2629                 if (option_exists(menu, "g") < 0) {
2630                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
2631                         return -1;
2632                 }
2633         }
2634         while (!res) {
2635                 while (menu->options[pos].option) {
2636                         if (!strcasecmp(menu->options[pos].option, exten)) {
2637                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
2638                                 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
2639                                 if (res < 0) {
2640                                         break;
2641                                 } else if (res & RES_UPONE) {
2642                                         return 0;
2643                                 } else if (res & RES_EXIT) {
2644                                         return res;
2645                                 } else if (res & RES_REPEAT) {
2646                                         int maxretries = res & 0xffff;
2647                                         if ((res & RES_RESTART) == RES_RESTART) {
2648                                                 retries = 0;
2649                                         } else {
2650                                                 retries++;
2651                                         }
2652                                         if (!maxretries) {
2653                                                 maxretries = 3;
2654                                         }
2655                                         if ((maxretries > 0) && (retries >= maxretries)) {
2656                                                 ast_debug(1, "Max retries %d exceeded\n", maxretries);
2657                                                 return -2;
2658                                         } else {
2659                                                 if (option_exists(menu, "g") > -1) {
2660                                                         strcpy(exten, "g");
2661                                                 } else if (option_exists(menu, "s") > -1) {
2662                                                         strcpy(exten, "s");
2663                                                 }
2664                                         }
2665                                         pos = 0;
2666                                         continue;
2667                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
2668                                         ast_debug(1, "Got start of extension, %c\n", res);
2669                                         exten[1] = '\0';
2670                                         exten[0] = res;
2671                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
2672                                                 break;
2673                                         }
2674                                         if (option_exists(menu, exten) < 0) {
2675                                                 if (option_exists(menu, "i")) {
2676                                                         ast_debug(1, "Invalid extension entered, going to 'i'!\n");
2677                                                         strcpy(exten, "i");
2678                                                         pos = 0;
2679                                                         continue;
2680                                                 } else {
2681                                                         ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
2682                                                         res = -2;
2683                                                         break;
2684                                                 }
2685                                         } else {
2686                                                 ast_debug(1, "New existing extension: %s\n", exten);
2687                                                 pos = 0;
2688                                                 continue;
2689                                         }
2690                                 }
2691                         }
2692                         pos++;
2693                 }
2694                 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
2695                 pos = 0;
2696                 if (!strcasecmp(exten, "s")) {
2697                         strcpy(exten, "g");
2698                 } else {
2699                         break;
2700                 }
2701         }
2702         return res;
2703 }
2704
2705 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2706 {
2707         int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
2708         /* Hide internal coding */
2709         return res > 0 ? 0 : res;
2710 }
2711
2712 char *ast_read_textfile(const char *filename)
2713 {
2714         int fd, count = 0, res;
2715         char *output = NULL;
2716         struct stat filesize;
2717
2718         if (stat(filename, &filesize) == -1) {
2719                 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
2720                 return NULL;
2721         }
2722
2723         count = filesize.st_size + 1;
2724
2725         if ((fd = open(filename, O_RDONLY)) < 0) {
2726                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
2727                 return NULL;
2728         }
2729
2730         if ((output = ast_malloc(count))) {
2731                 res = read(fd, output, count - 1);
2732                 if (res == count - 1) {
2733                         output[res] = '\0';
2734                 } else {
2735                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
2736                         ast_free(output);
2737                         output = NULL;
2738                 }
2739         }
2740
2741         close(fd);
2742
2743         return output;
2744 }
2745
2746 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
2747 {
2748         char *s, *arg;
2749         int curarg, res = 0;
2750         unsigned int argloc;
2751         struct ast_flags *flags = _flags;
2752         struct ast_flags64 *flags64 = _flags;
2753
2754         if (flaglen == 32) {
2755                 ast_clear_flag(flags, AST_FLAGS_ALL);
2756         } else {
2757                 flags64->flags = 0;
2758         }
2759
2760         if (!optstr) {
2761                 return 0;
2762         }
2763
2764         s = optstr;
2765         while (*s) {
2766                 curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
2767                 argloc = options[curarg].arg_index;
2768                 if (*s == '(') {
2769                         int paren = 1, quote = 0;
2770                         int parsequotes = (s[1] == '"') ? 1 : 0;
2771
2772                         /* Has argument */
2773                         arg = ++s;
2774                         for (; *s; s++) {
2775                                 if (*s == '(' && !quote) {
2776                                         paren++;
2777                                 } else if (*s == ')' && !quote) {
2778                                         /* Count parentheses, unless they're within quotes (or backslashed, below) */
2779                                         paren--;
2780                                 } else if (*s == '"' && parsequotes) {
2781                                         /* Leave embedded quotes alone, unless they are the first character */
2782                                         quote = quote ? 0 : 1;
2783                                         ast_copy_string(s, s + 1, INT_MAX);
2784                                         s--;
2785                                 } else if (*s == '\\') {
2786                                         if (!quote) {
2787                                                 /* If a backslash is found outside of quotes, remove it */
2788                                                 ast_copy_string(s, s + 1, INT_MAX);
2789                                         } else if (quote && s[1] == '"') {
2790                                                 /* Backslash for a quote character within quotes, remove the backslash */
2791                                                 ast_copy_string(s, s + 1, INT_MAX);
2792                                         } else {
2793                                                 /* Backslash within quotes, keep both characters */
2794                                                 s++;
2795                                         }
2796                                 }
2797
2798                                 if (paren == 0) {
2799                                         break;
2800                                 }
2801                         }
2802                         /* This will find the closing paren we found above, or none, if the string ended before we found one. */
2803                         if ((s = strchr(s, ')'))) {
2804                                 if (argloc) {
2805                                         args[argloc - 1] = arg;
2806                                 }
2807                                 *s++ = '\0';
2808                         } else {
2809                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
2810                                 res = -1;
2811                                 break;
2812                         }
2813                 } else if (argloc) {
2814                         args[argloc - 1] = "";
2815                 }
2816                 if (flaglen == 32) {
2817                         ast_set_flag(flags, options[curarg].flag);
2818                 } else {
2819                         ast_set_flag64(flags64, options[curarg].flag);
2820                 }
2821         }
2822
2823         return res;
2824 }
2825
2826 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
2827 {
2828         return parse_options(options, flags, args, optstr, 32);
2829 }
2830
2831 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
2832 {
2833         return parse_options(options, flags, args, optstr, 64);
2834 }
2835
2836 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
2837 {
2838         unsigned int i, found = 0;
2839         for (i = 32; i < 128 && found < len; i++) {
2840                 if (ast_test_flag64(flags, options[i].flag)) {
2841                         buf[found++] = i;
2842                 }
2843         }
2844         buf[found] = '\0';
2845 }
2846
2847 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
2848 {
2849         int i;
2850         *consumed = 1;
2851         *result = 0;
2852         if (ast_strlen_zero(stream)) {
2853                 *consumed = 0;
2854                 return -1;
2855         }
2856
2857         if (*stream == '\\') {
2858                 *consumed = 2;
2859                 switch (*(stream + 1)) {
2860                 case 'n':
2861                         *result = '\n';
2862                         break;
2863                 case 'r':
2864                         *result = '\r';
2865                         break;
2866                 case 't':
2867                         *result = '\t';
2868                         break;
2869                 case 'x':
2870                         /* Hexadecimal */
2871                         if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
2872                                 *consumed = 3;
2873                                 if (*(stream + 2) <= '9') {
2874                                         *result = *(stream + 2) - '0';
2875                                 } else if (*(stream + 2) <= 'F') {
2876                                         *result = *(stream + 2) - 'A' + 10;
2877                                 } else {
2878                                         *result = *(stream + 2) - 'a' + 10;
2879                                 }
2880                         } else {
2881                                 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
2882                                 return -1;
2883                         }
2884
2885                         if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
2886                                 *consumed = 4;
2887                                 *result <<= 4;
2888                                 if (*(stream + 3) <= '9') {
2889                                         *result += *(stream + 3) - '0';
2890                                 } else if (*(stream + 3) <= 'F') {
2891                                         *result += *(stream + 3) - 'A' + 10;
2892                                 } else {
2893                                         *result += *(stream + 3) - 'a' + 10;
2894                                 }
2895                         }
2896                         break;
2897                 case '0':
2898                         /* Octal */
2899                         *consumed = 2;
2900                         for (i = 2; ; i++) {
2901                                 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
2902                                         (*consumed)++;
2903                                         ast_debug(5, "result was %d, ", *result);
2904                                         *result <<= 3;
2905                                         *result += *(stream + i) - '0';
2906                                         ast_debug(5, "is now %d\n", *result);
2907                                 } else {
2908                                         break;
2909                                 }
2910                         }
2911                         break;
2912                 default:
2913                         *result = *(stream + 1);
2914                 }
2915         } else {
2916                 *result = *stream;
2917                 *consumed = 1;
2918         }
2919         return 0;
2920 }
2921
2922 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
2923 {
2924         char *cur = result;
2925         size_t consumed;
2926
2927         while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
2928                 cur++;
2929                 stream += consumed;
2930         }
2931         *cur = '\0';
2932         return result;
2933 }
2934
2935 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
2936 {
2937         char next, *buf;
2938         size_t offset = 0;
2939         size_t consumed;
2940
2941         if (strchr(stream, '\\')) {
2942                 while (!ast_get_encoded_char(stream, &next, &consumed)) {
2943                         if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
2944                                 ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
2945                         }
2946                         if (offset + 2 > ast_str_size(*str)) {
2947                                 break;
2948                         }
2949                         buf = ast_str_buffer(*str);
2950                         buf[offset++] = next;
2951                         stream += consumed;
2952                 }
2953                 buf = ast_str_buffer(*str);
2954                 buf[offset++] = '\0';
2955                 ast_str_update(*str);
2956         } else {
2957                 ast_str_set(str, maxlen, "%s", stream);
2958         }
2959         return 0;
2960 }
2961
2962 void ast_close_fds_above_n(int n)
2963 {
2964         closefrom(n + 1);
2965 }
2966
2967 int ast_safe_fork(int stop_reaper)
2968 {
2969         sigset_t signal_set, old_set;
2970         int pid;
2971
2972         /* Don't let the default signal handler for children reap our status */
2973         if (stop_reaper) {
2974                 ast_replace_sigchld();
2975         }
2976
2977         /* GCC 4.9 gives a bogus "right-hand operand of comma expression has
2978          * no effect" warning */
2979         (void) sigfillset(&signal_set);
2980         pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
2981
2982         pid = fork();
2983
2984         if (pid != 0) {
2985                 /* Fork failed or parent */
2986                 pthread_sigmask(SIG_SETMASK, &old_set, NULL);
2987                 if (!stop_reaper && pid > 0) {
2988                         struct zombie *cur = ast_calloc(1, sizeof(*cur));
2989                         if (cur) {
2990                                 cur->pid = pid;
2991                                 AST_LIST_LOCK(&zombies);
2992                                 AST_LIST_INSERT_TAIL(&zombies, cur, list);
2993                                 AST_LIST_UNLOCK(&zombies);
2994                                 if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
2995                                         if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
2996                                                 ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
2997                                                 shaun_of_the_dead_thread = AST_PTHREADT_NULL;
2998                                         }
2999                                 }
3000                         }
3001                 }
3002                 return pid;
3003         } else {
3004                 /* Child */
3005 #ifdef HAVE_CAP
3006                 cap_t cap = cap_from_text("cap_net_admin-eip");
3007
3008                 if (cap_set_proc(cap)) {
3009                         ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
3010                 }
3011                 cap_free(cap);
3012 #endif
3013
3014                 /* Before we unblock our signals, return our trapped signals back to the defaults */
3015                 signal(SIGHUP, SIG_DFL);
3016                 signal(SIGCHLD, SIG_DFL);
3017                 signal(SIGINT, SIG_DFL);
3018                 signal(SIGURG, SIG_DFL);
3019                 signal(SIGTERM, SIG_DFL);
3020                 signal(SIGPIPE, SIG_DFL);
3021                 signal(SIGXFSZ, SIG_DFL);
3022
3023                 /* unblock important signal handlers */
3024                 if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
3025                         ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
3026                         _exit(1);
3027                 }
3028
3029                 return pid;
3030         }
3031 }
3032
3033 void ast_safe_fork_cleanup(void)
3034 {
3035         ast_unreplace_sigchld();
3036 }
3037
3038 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
3039 {
3040         int res;
3041         char u[10];
3042 #ifdef HAVE_LONG_DOUBLE_WIDER
3043         long double amount;
3044         #define FMT "%30Lf%9s"
3045 #else
3046         double amount;
3047         #define FMT "%30lf%9s"
3048 #endif
3049         if (!timestr) {
3050                 return -1;
3051         }
3052
3053         res = sscanf(timestr, FMT, &amount, u);
3054
3055         if (res == 0 || res == EOF) {
3056 #undef FMT
3057                 return -1;
3058         } else if (res == 2) {
3059                 switch (u[0]) {
3060                 case 'h':
3061                 case 'H':
3062                         unit = TIMELEN_HOURS;
3063                         if (u[1] != '\0') {
3064                                 return -1;
3065                         }
3066                         break;
3067                 case 's':
3068                 case 'S':
3069                         unit = TIMELEN_SECONDS;
3070                         if (u[1] != '\0') {
3071                                 return -1;
3072                         }
3073                         break;
3074                 case 'm':
3075                 case 'M':
3076                         if (toupper(u[1]) == 'S') {
3077                                 unit = TIMELEN_MILLISECONDS;
3078                                 if (u[2] != '\0') {
3079                                         return -1;
3080                                 }
3081                         } else if (u[1] == '\0') {
3082                                 unit = TIMELEN_MINUTES;
3083                         } else {
3084                                 return -1;
3085                         }
3086                         break;
3087                 default:
3088                         return -1;
3089                 }
3090         }
3091
3092         switch (unit) {
3093         case TIMELEN_HOURS:
3094                 amount *= 60;
3095                 /* fall-through */
3096         case TIMELEN_MINUTES:
3097                 amount *= 60;
3098                 /* fall-through */
3099         case TIMELEN_SECONDS:
3100                 amount *= 1000;
3101                 /* fall-through */
3102         case TIMELEN_MILLISECONDS:
3103                 ;
3104         }
3105         *result = amount > INT_MAX ? INT_MAX : (int) amount;
3106         return 0;
3107 }
3108
3109
3110
3111 static void mwi_state_dtor(void *obj)
3112 {
3113         struct ast_mwi_state *mwi_state = obj;
3114         ast_string_field_free_memory(mwi_state);
3115         ao2_cleanup(mwi_state->snapshot);
3116         mwi_state->snapshot = NULL;
3117 }
3118
3119 struct stasis_topic *ast_mwi_topic_all(void)
3120 {
3121         return mwi_topic_all;
3122 }
3123
3124 struct stasis_cache *ast_mwi_state_cache(void)
3125 {
3126         return mwi_state_cache;
3127 }
3128
3129 struct stasis_topic *ast_mwi_topic_cached(void)
3130 {
3131         return stasis_caching_get_topic(mwi_topic_cached);
3132 }
3133
3134 struct stasis_topic *ast_mwi_topic(const char *uniqueid)
3135 {
3136         return stasis_topic_pool_get_topic(mwi_topic_pool, uniqueid);
3137 }
3138
3139 struct ast_mwi_state *ast_mwi_create(const char *mailbox, const char *context)
3140 {
3141         struct ast_mwi_state *mwi_state;
3142
3143         ast_assert(!ast_strlen_zero(mailbox));
3144
3145         mwi_state = ao2_alloc(sizeof(*mwi_state), mwi_state_dtor);
3146         if (!mwi_state) {
3147                 return NULL;
3148         }
3149
3150         if (ast_string_field_init(mwi_state, 256)) {
3151                 ao2_ref(mwi_state, -1);
3152                 return NULL;
3153         }
3154         if (!ast_strlen_zero(context)) {
3155                 ast_string_field_build(mwi_state, uniqueid, "%s@%s", mailbox, context);
3156         } else {
3157                 ast_string_field_set(mwi_state, uniqueid, mailbox);
3158         }
3159
3160         return mwi_state;
3161 }
3162
3163 /*!
3164  * \internal
3165  * \brief Create a MWI state snapshot message.
3166  * \since 12.2.0
3167  *
3168  * \param[in] mailbox The mailbox identifier string.
3169  * \param[in] context The context this mailbox resides in (NULL or "" if only using mailbox)
3170  * \param[in] new_msgs The number of new messages in this mailbox
3171  * \param[in] old_msgs The number of old messages in this mailbox
3172  * \param[in] channel_id A unique identifier for a channel associated with this
3173  * change in mailbox state
3174  * \param[in] eid The EID of the server that originally published the message
3175  *
3176  * \retval message on success.  Use ao2_cleanup() when done with it.
3177  * \retval NULL on error.
3178  */
3179 static struct stasis_message *mwi_state_create_message(
3180         const char *mailbox,
3181         const char *context,