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