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