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