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