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