Clean up and ensure proper usage of alloca()
[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 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #ifdef HAVE_SYS_STAT_H
35 #include <sys/stat.h>
36 #endif
37 #include <regex.h>          /* for regcomp(3) */
38 #include <sys/file.h>       /* for flock(2) */
39 #include <signal.h>         /* for pthread_sigmask(3) */
40 #include <stdlib.h>         /* for closefrom(3) */
41 #include <sys/types.h>
42 #include <sys/wait.h>       /* for waitpid(2) */
43 #ifndef HAVE_CLOSEFROM
44 #include <dirent.h>         /* for opendir(3)   */
45 #endif
46 #ifdef HAVE_CAP
47 #include <sys/capability.h>
48 #endif /* HAVE_CAP */
49
50 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
51 #include "asterisk/channel.h"
52 #include "asterisk/pbx.h"
53 #include "asterisk/file.h"
54 #include "asterisk/app.h"
55 #include "asterisk/dsp.h"
56 #include "asterisk/utils.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/indications.h"
59 #include "asterisk/linkedlists.h"
60 #include "asterisk/threadstorage.h"
61 #include "asterisk/test.h"
62 #include "asterisk/module.h"
63
64 AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
65
66 static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
67
68 struct zombie {
69         pid_t pid;
70         AST_LIST_ENTRY(zombie) list;
71 };
72
73 static AST_LIST_HEAD_STATIC(zombies, zombie);
74
75 static void *shaun_of_the_dead(void *data)
76 {
77         struct zombie *cur;
78         int status;
79         for (;;) {
80                 if (!AST_LIST_EMPTY(&zombies)) {
81                         /* Don't allow cancellation while we have a lock. */
82                         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
83                         AST_LIST_LOCK(&zombies);
84                         AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
85                                 if (waitpid(cur->pid, &status, WNOHANG) != 0) {
86                                         AST_LIST_REMOVE_CURRENT(list);
87                                         ast_free(cur);
88                                 }
89                         }
90                         AST_LIST_TRAVERSE_SAFE_END
91                         AST_LIST_UNLOCK(&zombies);
92                         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
93                 }
94                 pthread_testcancel();
95                 /* Wait for 60 seconds, without engaging in a busy loop. */
96                 ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
97         }
98         return NULL;
99 }
100
101
102 #define AST_MAX_FORMATS 10
103
104 static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
105
106 /*!
107  * \brief This function presents a dialtone and reads an extension into 'collect'
108  * which must be a pointer to a **pre-initialized** array of char having a
109  * size of 'size' suitable for writing to.  It will collect no more than the smaller
110  * of 'maxlen' or 'size' minus the original strlen() of collect digits.
111  * \param chan struct.
112  * \param context
113  * \param collect
114  * \param size
115  * \param maxlen
116  * \param timeout timeout in milliseconds
117  *
118  * \return 0 if extension does not exist, 1 if extension exists
119 */
120 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
121 {
122         struct ast_tone_zone_sound *ts;
123         int res = 0, x = 0;
124
125         if (maxlen > size) {
126                 maxlen = size;
127         }
128
129         if (!timeout) {
130                 if (ast_channel_pbx(chan) && ast_channel_pbx(chan)->dtimeoutms) {
131                         timeout = ast_channel_pbx(chan)->dtimeoutms;
132                 } else {
133                         timeout = 5000;
134                 }
135         }
136
137         if ((ts = ast_get_indication_tone(ast_channel_zone(chan), "dial"))) {
138                 res = ast_playtones_start(chan, 0, ts->data, 0);
139                 ts = ast_tone_zone_sound_unref(ts);
140         } else {
141                 ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
142         }
143
144         for (x = strlen(collect); x < maxlen; ) {
145                 res = ast_waitfordigit(chan, timeout);
146                 if (!ast_ignore_pattern(context, collect)) {
147                         ast_playtones_stop(chan);
148                 }
149                 if (res < 1) {
150                         break;
151                 }
152                 if (res == '#') {
153                         break;
154                 }
155                 collect[x++] = res;
156                 if (!ast_matchmore_extension(chan, context, collect, 1,
157                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
158                         break;
159                 }
160         }
161
162         if (res >= 0) {
163                 res = ast_exists_extension(chan, context, collect, 1,
164                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL)) ? 1 : 0;
165         }
166
167         return res;
168 }
169
170 /*!
171  * \brief ast_app_getdata
172  * \param c The channel to read from
173  * \param prompt The file to stream to the channel
174  * \param s The string to read in to.  Must be at least the size of your length
175  * \param maxlen How many digits to read (maximum)
176  * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
177  *      "ludicrous time" (essentially never times out) */
178 enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
179 {
180         int res = 0, to, fto;
181         char *front, *filename;
182
183         /* XXX Merge with full version? XXX */
184
185         if (maxlen)
186                 s[0] = '\0';
187
188         if (!prompt)
189                 prompt = "";
190
191         filename = ast_strdupa(prompt);
192         while ((front = strsep(&filename, "&"))) {
193                 ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", front, ast_channel_name(c));
194                 if (!ast_strlen_zero(front)) {
195                         res = ast_streamfile(c, front, ast_channel_language(c));
196                         if (res)
197                                 continue;
198                 }
199                 if (ast_strlen_zero(filename)) {
200                         /* set timeouts for the last prompt */
201                         fto = ast_channel_pbx(c) ? ast_channel_pbx(c)->rtimeoutms : 6000;
202                         to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
203
204                         if (timeout > 0) {
205                                 fto = to = timeout;
206                         }
207                         if (timeout < 0) {
208                                 fto = to = 1000000000;
209                         }
210                 } else {
211                         /* there is more than one prompt, so
212                          * get rid of the long timeout between
213                          * prompts, and make it 50ms */
214                         fto = 50;
215                         to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
216                 }
217                 res = ast_readstring(c, s, maxlen, to, fto, "#");
218                 if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
219                         return res;
220                 }
221                 if (!ast_strlen_zero(s)) {
222                         return res;
223                 }
224         }
225
226         return res;
227 }
228
229 /* The lock type used by ast_lock_path() / ast_unlock_path() */
230 static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
231
232 int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
233 {
234         int res, to = 2000, fto = 6000;
235
236         if (!ast_strlen_zero(prompt)) {
237                 res = ast_streamfile(c, prompt, ast_channel_language(c));
238                 if (res < 0) {
239                         return res;
240                 }
241         }
242
243         if (timeout > 0) {
244                 fto = to = timeout;
245         }
246         if (timeout < 0) {
247                 fto = to = 1000000000;
248         }
249
250         res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
251
252         return res;
253 }
254
255 int ast_app_exec_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_args)
256 {
257         struct ast_app *macro_app;
258         int res;
259
260         macro_app = pbx_findapp("Macro");
261         if (!macro_app) {
262                 ast_log(LOG_WARNING,
263                         "Cannot run 'Macro(%s)'.  The application is not available.\n", macro_args);
264                 return -1;
265         }
266         if (autoservice_chan) {
267                 ast_autoservice_start(autoservice_chan);
268         }
269
270         ast_debug(4, "%s Original location: %s,%s,%d\n", ast_channel_name(macro_chan),
271                 ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
272                 ast_channel_priority(macro_chan));
273
274         res = pbx_exec(macro_chan, macro_app, macro_args);
275         ast_debug(4, "Macro exited with status %d\n", res);
276
277         /*
278          * Assume anything negative from Macro is an error.
279          * Anything else is success.
280          */
281         if (res < 0) {
282                 res = -1;
283         } else {
284                 res = 0;
285         }
286
287         ast_debug(4, "%s Ending location: %s,%s,%d\n", ast_channel_name(macro_chan),
288                 ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
289                 ast_channel_priority(macro_chan));
290
291         if (autoservice_chan) {
292                 ast_autoservice_stop(autoservice_chan);
293         }
294         return res;
295 }
296
297 int ast_app_run_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_name, const char *macro_args)
298 {
299         int res;
300         char *args_str;
301         size_t args_len;
302
303         if (ast_strlen_zero(macro_args)) {
304                 return ast_app_exec_macro(autoservice_chan, macro_chan, macro_name);
305         }
306
307         /* Create the Macro application argument string. */
308         args_len = strlen(macro_name) + strlen(macro_args) + 2;
309         args_str = ast_malloc(args_len);
310         if (!args_str) {
311                 return -1;
312         }
313         snprintf(args_str, args_len, "%s,%s", macro_name, macro_args);
314
315         res = ast_app_exec_macro(autoservice_chan, macro_chan, args_str);
316         ast_free(args_str);
317         return res;
318 }
319
320 static const struct ast_app_stack_funcs *app_stack_callbacks;
321
322 void ast_install_stack_functions(const struct ast_app_stack_funcs *funcs)
323 {
324         app_stack_callbacks = funcs;
325 }
326
327 const char *ast_app_expand_sub_args(struct ast_channel *chan, const char *args)
328 {
329         const struct ast_app_stack_funcs *funcs;
330         const char *new_args;
331
332         funcs = app_stack_callbacks;
333         if (!funcs || !funcs->expand_sub_args) {
334                 ast_log(LOG_WARNING,
335                         "Cannot expand 'Gosub(%s)' arguments.  The app_stack module is not available.\n",
336                         args);
337                 return NULL;
338         }
339         ast_module_ref(funcs->module);
340
341         new_args = funcs->expand_sub_args(chan, args);
342         ast_module_unref(funcs->module);
343         return new_args;
344 }
345
346 int ast_app_exec_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_args, int ignore_hangup)
347 {
348         const struct ast_app_stack_funcs *funcs;
349         int res;
350
351         funcs = app_stack_callbacks;
352         if (!funcs || !funcs->run_sub) {
353                 ast_log(LOG_WARNING,
354                         "Cannot run 'Gosub(%s)'.  The app_stack module is not available.\n",
355                         sub_args);
356                 return -1;
357         }
358         ast_module_ref(funcs->module);
359
360         if (autoservice_chan) {
361                 ast_autoservice_start(autoservice_chan);
362         }
363
364         res = funcs->run_sub(sub_chan, sub_args, ignore_hangup);
365         ast_module_unref(funcs->module);
366
367         if (autoservice_chan) {
368                 ast_autoservice_stop(autoservice_chan);
369         }
370         return res;
371 }
372
373 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)
374 {
375         int res;
376         char *args_str;
377         size_t args_len;
378
379         if (ast_strlen_zero(sub_args)) {
380                 return ast_app_exec_sub(autoservice_chan, sub_chan, sub_location, ignore_hangup);
381         }
382
383         /* Create the Gosub application argument string. */
384         args_len = strlen(sub_location) + strlen(sub_args) + 3;
385         args_str = ast_malloc(args_len);
386         if (!args_str) {
387                 return -1;
388         }
389         snprintf(args_str, args_len, "%s(%s)", sub_location, sub_args);
390
391         res = ast_app_exec_sub(autoservice_chan, sub_chan, args_str, ignore_hangup);
392         ast_free(args_str);
393         return res;
394 }
395
396 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
397 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
398 static int (*ast_inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs) = NULL;
399 static int (*ast_sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context) = NULL;
400 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
401 static int (*ast_copy_recording_to_vm_func)(struct ast_vm_recording_data *vm_rec_data) = NULL;
402 static const char *(*ast_vm_index_to_foldername_func)(int id) = NULL;
403 static struct ast_vm_mailbox_snapshot *(*ast_vm_mailbox_snapshot_create_func)(const char *mailbox,
404         const char *context,
405         const char *folder,
406         int descending,
407         enum ast_vm_snapshot_sort_val sort_val,
408         int combine_INBOX_and_OLD) = NULL;
409 static struct ast_vm_mailbox_snapshot *(*ast_vm_mailbox_snapshot_destroy_func)(struct ast_vm_mailbox_snapshot *mailbox_snapshot) = NULL;
410 static int (*ast_vm_msg_move_func)(const char *mailbox,
411         const char *context,
412         size_t num_msgs,
413         const char *oldfolder,
414         const char *old_msg_ids[],
415         const char *newfolder) = NULL;
416 static int (*ast_vm_msg_remove_func)(const char *mailbox,
417         const char *context,
418         size_t num_msgs,
419         const char *folder,
420         const char *msgs[]) = NULL;
421 static int (*ast_vm_msg_forward_func)(const char *from_mailbox,
422         const char *from_context,
423         const char *from_folder,
424         const char *to_mailbox,
425         const char *to_context,
426         const char *to_folder,
427         size_t num_msgs,
428         const char *msg_ids[],
429         int delete_old) = NULL;
430 static int (*ast_vm_msg_play_func)(struct ast_channel *chan,
431         const char *mailbox,
432         const char *context,
433         const char *folder,
434         const char *msg_num,
435         ast_vm_msg_play_cb cb) = NULL;
436
437 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
438                               int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
439                               int (*inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs),
440                               int (*messagecount_func)(const char *context, const char *mailbox, const char *folder),
441                               int (*sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context),
442                               int (*copy_recording_to_vm_func)(struct ast_vm_recording_data *vm_rec_data),
443                               const char *vm_index_to_foldername_func(int id),
444                               struct ast_vm_mailbox_snapshot *(*vm_mailbox_snapshot_create_func)(const char *mailbox,
445                                 const char *context,
446                                 const char *folder,
447                                 int descending,
448                                 enum ast_vm_snapshot_sort_val sort_val,
449                                 int combine_INBOX_and_OLD),
450                               struct ast_vm_mailbox_snapshot *(*vm_mailbox_snapshot_destroy_func)(struct ast_vm_mailbox_snapshot *mailbox_snapshot),
451                               int (*vm_msg_move_func)(const char *mailbox,
452                                 const char *context,
453                                 size_t num_msgs,
454                                 const char *oldfolder,
455                                 const char *old_msg_ids[],
456                                 const char *newfolder),
457                               int (*vm_msg_remove_func)(const char *mailbox,
458                                 const char *context,
459                                 size_t num_msgs,
460                                 const char *folder,
461                                 const char *msgs[]),
462                               int (*vm_msg_forward_func)(const char *from_mailbox,
463                                 const char *from_context,
464                                 const char *from_folder,
465                                 const char *to_mailbox,
466                                 const char *to_context,
467                                 const char *to_folder,
468                                 size_t num_msgs,
469                                 const char *msg_ids[],
470                                 int delete_old),
471                               int (*vm_msg_play_func)(struct ast_channel *chan,
472                                 const char *mailbox,
473                                 const char *context,
474                                 const char *folder,
475                                 const char *msg_num,
476                                 ast_vm_msg_play_cb cb))
477 {
478         ast_has_voicemail_func = has_voicemail_func;
479         ast_inboxcount_func = inboxcount_func;
480         ast_inboxcount2_func = inboxcount2_func;
481         ast_messagecount_func = messagecount_func;
482         ast_sayname_func = sayname_func;
483         ast_copy_recording_to_vm_func = copy_recording_to_vm_func;
484         ast_vm_index_to_foldername_func = vm_index_to_foldername_func;
485         ast_vm_mailbox_snapshot_create_func = vm_mailbox_snapshot_create_func;
486         ast_vm_mailbox_snapshot_destroy_func = vm_mailbox_snapshot_destroy_func;
487         ast_vm_msg_move_func = vm_msg_move_func;
488         ast_vm_msg_remove_func = vm_msg_remove_func;
489         ast_vm_msg_forward_func = vm_msg_forward_func;
490         ast_vm_msg_play_func = vm_msg_play_func;
491 }
492
493 void ast_uninstall_vm_functions(void)
494 {
495         ast_has_voicemail_func = NULL;
496         ast_inboxcount_func = NULL;
497         ast_inboxcount2_func = NULL;
498         ast_messagecount_func = NULL;
499         ast_sayname_func = NULL;
500         ast_copy_recording_to_vm_func = NULL;
501         ast_vm_index_to_foldername_func = NULL;
502         ast_vm_mailbox_snapshot_create_func = NULL;
503         ast_vm_mailbox_snapshot_destroy_func = NULL;
504         ast_vm_msg_move_func = NULL;
505         ast_vm_msg_remove_func = NULL;
506         ast_vm_msg_forward_func = NULL;
507         ast_vm_msg_play_func = NULL;
508 }
509
510 #ifdef TEST_FRAMEWORK
511 int (*ast_vm_test_create_user_func)(const char *context, const char *mailbox) = NULL;
512 int (*ast_vm_test_destroy_user_func)(const char *context, const char *mailbox) = NULL;
513
514 void ast_install_vm_test_functions(int (*vm_test_create_user_func)(const char *context, const char *mailbox),
515                                    int (*vm_test_destroy_user_func)(const char *context, const char *mailbox))
516 {
517         ast_vm_test_create_user_func = vm_test_create_user_func;
518         ast_vm_test_destroy_user_func = vm_test_destroy_user_func;
519 }
520
521 void ast_uninstall_vm_test_functions(void)
522 {
523         ast_vm_test_create_user_func = NULL;
524         ast_vm_test_destroy_user_func = NULL;
525 }
526 #endif
527
528 int ast_app_has_voicemail(const char *mailbox, const char *folder)
529 {
530         static int warned = 0;
531         if (ast_has_voicemail_func) {
532                 return ast_has_voicemail_func(mailbox, folder);
533         }
534
535         if (warned++ % 10 == 0) {
536                 ast_verb(3, "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
537         }
538         return 0;
539 }
540
541 /*!
542  * \internal
543  * \brief Function used as a callback for ast_copy_recording_to_vm when a real one isn't installed.
544  * \param vm_rec_data Stores crucial information about the voicemail that will basically just be used
545  * to figure out what the name of the recipient was supposed to be
546  */
547 int ast_app_copy_recording_to_vm(struct ast_vm_recording_data *vm_rec_data)
548 {
549         static int warned = 0;
550
551         if (ast_copy_recording_to_vm_func) {
552                 return ast_copy_recording_to_vm_func(vm_rec_data);
553         }
554
555         if (warned++ % 10 == 0) {
556                 ast_verb(3, "copy recording to voicemail called to copy %s.%s to %s@%s, but voicemail not loaded.\n",
557                         vm_rec_data->recording_file, vm_rec_data->recording_ext,
558                         vm_rec_data->mailbox, vm_rec_data->context);
559         }
560
561         return -1;
562 }
563
564 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
565 {
566         static int warned = 0;
567         if (newmsgs) {
568                 *newmsgs = 0;
569         }
570         if (oldmsgs) {
571                 *oldmsgs = 0;
572         }
573         if (ast_inboxcount_func) {
574                 return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
575         }
576
577         if (warned++ % 10 == 0) {
578                 ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
579         }
580
581         return 0;
582 }
583
584 int ast_app_inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
585 {
586         static int warned = 0;
587         if (newmsgs) {
588                 *newmsgs = 0;
589         }
590         if (oldmsgs) {
591                 *oldmsgs = 0;
592         }
593         if (urgentmsgs) {
594                 *urgentmsgs = 0;
595         }
596         if (ast_inboxcount2_func) {
597                 return ast_inboxcount2_func(mailbox, urgentmsgs, newmsgs, oldmsgs);
598         }
599
600         if (warned++ % 10 == 0) {
601                 ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
602         }
603
604         return 0;
605 }
606
607 int ast_app_sayname(struct ast_channel *chan, const char *mailbox, const char *context)
608 {
609         if (ast_sayname_func) {
610                 return ast_sayname_func(chan, mailbox, context);
611         }
612         return -1;
613 }
614
615 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
616 {
617         static int warned = 0;
618         if (ast_messagecount_func) {
619                 return ast_messagecount_func(context, mailbox, folder);
620         }
621
622         if (!warned) {
623                 warned++;
624                 ast_verb(3, "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
625         }
626
627         return 0;
628 }
629
630 const char *ast_vm_index_to_foldername(int id)
631 {
632         if (ast_vm_index_to_foldername_func) {
633                 return ast_vm_index_to_foldername_func(id);
634         }
635         return NULL;
636 }
637
638 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_create(const char *mailbox,
639         const char *context,
640         const char *folder,
641         int descending,
642         enum ast_vm_snapshot_sort_val sort_val,
643         int combine_INBOX_and_OLD)
644 {
645         if (ast_vm_mailbox_snapshot_create_func) {
646                 return ast_vm_mailbox_snapshot_create_func(mailbox, context, folder, descending, sort_val, combine_INBOX_and_OLD);
647         }
648         return NULL;
649 }
650
651 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot)
652 {
653         if (ast_vm_mailbox_snapshot_destroy_func) {
654                 return ast_vm_mailbox_snapshot_destroy_func(mailbox_snapshot);
655         }
656         return NULL;
657 }
658
659 int ast_vm_msg_move(const char *mailbox,
660         const char *context,
661         size_t num_msgs,
662         const char *oldfolder,
663         const char *old_msg_ids[],
664         const char *newfolder)
665 {
666         if (ast_vm_msg_move_func) {
667                 return ast_vm_msg_move_func(mailbox, context, num_msgs, oldfolder, old_msg_ids, newfolder);
668         }
669         return 0;
670 }
671
672 int ast_vm_msg_remove(const char *mailbox,
673         const char *context,
674         size_t num_msgs,
675         const char *folder,
676         const char *msgs[])
677 {
678         if (ast_vm_msg_remove_func) {
679                 return ast_vm_msg_remove_func(mailbox, context, num_msgs, folder, msgs);
680         }
681         return 0;
682 }
683
684 int ast_vm_msg_forward(const char *from_mailbox,
685         const char *from_context,
686         const char *from_folder,
687         const char *to_mailbox,
688         const char *to_context,
689         const char *to_folder,
690         size_t num_msgs,
691         const char *msg_ids[],
692         int delete_old)
693 {
694         if (ast_vm_msg_forward_func) {
695                 return ast_vm_msg_forward_func(from_mailbox, from_context, from_folder, to_mailbox, to_context, to_folder, num_msgs, msg_ids, delete_old);
696         }
697         return 0;
698 }
699
700 int ast_vm_msg_play(struct ast_channel *chan,
701         const char *mailbox,
702         const char *context,
703         const char *folder,
704         const char *msg_num,
705         ast_vm_msg_play_cb cb)
706 {
707         if (ast_vm_msg_play_func) {
708                 return ast_vm_msg_play_func(chan, mailbox, context, folder, msg_num, cb);
709         }
710         return 0;
711 }
712
713 #ifdef TEST_FRAMEWORK
714 int ast_vm_test_create_user(const char *context, const char *mailbox)
715 {
716         if (ast_vm_test_create_user_func) {
717                 return ast_vm_test_create_user_func(context, mailbox);
718         }
719         return 0;
720 }
721
722 int ast_vm_test_destroy_user(const char *context, const char *mailbox)
723 {
724         if (ast_vm_test_destroy_user_func) {
725                 return ast_vm_test_destroy_user_func(context, mailbox);
726         }
727         return 0;
728 }
729 #endif
730
731 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
732 {
733         const char *ptr;
734         int res = 0;
735         struct ast_silence_generator *silgen = NULL;
736
737         if (!between) {
738                 between = 100;
739         }
740
741         if (peer) {
742                 res = ast_autoservice_start(peer);
743         }
744
745         if (!res) {
746                 res = ast_waitfor(chan, 100);
747         }
748
749         /* ast_waitfor will return the number of remaining ms on success */
750         if (res < 0) {
751                 if (peer) {
752                         ast_autoservice_stop(peer);
753                 }
754                 return res;
755         }
756
757         if (ast_opt_transmit_silence) {
758                 silgen = ast_channel_start_silence_generator(chan);
759         }
760
761         for (ptr = digits; *ptr; ptr++) {
762                 if (*ptr == 'w') {
763                         /* 'w' -- wait half a second */
764                         if ((res = ast_safe_sleep(chan, 500))) {
765                                 break;
766                         }
767                 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
768                         /* Character represents valid DTMF */
769                         if (*ptr == 'f' || *ptr == 'F') {
770                                 /* ignore return values if not supported by channel */
771                                 ast_indicate(chan, AST_CONTROL_FLASH);
772                         } else {
773                                 ast_senddigit(chan, *ptr, duration);
774                         }
775                         /* pause between digits */
776                         if ((res = ast_safe_sleep(chan, between))) {
777                                 break;
778                         }
779                 } else {
780                         ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
781                 }
782         }
783
784         if (peer) {
785                 /* Stop autoservice on the peer channel, but don't overwrite any error condition
786                    that has occurred previously while acting on the primary channel */
787                 if (ast_autoservice_stop(peer) && !res) {
788                         res = -1;
789                 }
790         }
791
792         if (silgen) {
793                 ast_channel_stop_silence_generator(chan, silgen);
794         }
795
796         return res;
797 }
798
799 struct linear_state {
800         int fd;
801         int autoclose;
802         int allowoverride;
803         struct ast_format origwfmt;
804 };
805
806 static void linear_release(struct ast_channel *chan, void *params)
807 {
808         struct linear_state *ls = params;
809
810         if (ls->origwfmt.id && ast_set_write_format(chan, &ls->origwfmt)) {
811                 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", ast_channel_name(chan), ls->origwfmt.id);
812         }
813
814         if (ls->autoclose) {
815                 close(ls->fd);
816         }
817
818         ast_free(params);
819 }
820
821 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
822 {
823         short buf[2048 + AST_FRIENDLY_OFFSET / 2];
824         struct linear_state *ls = data;
825         struct ast_frame f = {
826                 .frametype = AST_FRAME_VOICE,
827                 .data.ptr = buf + AST_FRIENDLY_OFFSET / 2,
828                 .offset = AST_FRIENDLY_OFFSET,
829         };
830         int res;
831
832         ast_format_set(&f.subclass.format, AST_FORMAT_SLINEAR, 0);
833
834         len = samples * 2;
835         if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
836                 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" , len);
837                 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
838         }
839         res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
840         if (res > 0) {
841                 f.datalen = res;
842                 f.samples = res / 2;
843                 ast_write(chan, &f);
844                 if (res == len) {
845                         return 0;
846                 }
847         }
848         return -1;
849 }
850
851 static void *linear_alloc(struct ast_channel *chan, void *params)
852 {
853         struct linear_state *ls = params;
854
855         if (!params) {
856                 return NULL;
857         }
858
859         /* In this case, params is already malloc'd */
860         if (ls->allowoverride) {
861                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
862         } else {
863                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
864         }
865
866         ast_format_copy(&ls->origwfmt, ast_channel_writeformat(chan));
867
868         if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR)) {
869                 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", ast_channel_name(chan));
870                 ast_free(ls);
871                 ls = params = NULL;
872         }
873
874         return params;
875 }
876
877 static struct ast_generator linearstream =
878 {
879         .alloc = linear_alloc,
880         .release = linear_release,
881         .generate = linear_generator,
882 };
883
884 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
885 {
886         struct linear_state *lin;
887         char tmpf[256];
888         int res = -1;
889         int autoclose = 0;
890         if (fd < 0) {
891                 if (ast_strlen_zero(filename)) {
892                         return -1;
893                 }
894                 autoclose = 1;
895                 if (filename[0] == '/') {
896                         ast_copy_string(tmpf, filename, sizeof(tmpf));
897                 } else {
898                         snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
899                 }
900                 if ((fd = open(tmpf, O_RDONLY)) < 0) {
901                         ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
902                         return -1;
903                 }
904         }
905         if ((lin = ast_calloc(1, sizeof(*lin)))) {
906                 lin->fd = fd;
907                 lin->allowoverride = allowoverride;
908                 lin->autoclose = autoclose;
909                 res = ast_activate_generator(chan, &linearstream, lin);
910         }
911         return res;
912 }
913
914 static int control_streamfile(struct ast_channel *chan,
915         const char *file,
916         const char *fwd,
917         const char *rev,
918         const char *stop,
919         const char *suspend,
920         const char *restart,
921         int skipms,
922         long *offsetms,
923         ast_waitstream_fr_cb cb)
924 {
925         char *breaks = NULL;
926         char *end = NULL;
927         int blen = 2;
928         int res;
929         long pause_restart_point = 0;
930         long offset = 0;
931
932         if (!file) {
933                 return -1;
934         }
935         if (offsetms) {
936                 offset = *offsetms * 8; /* XXX Assumes 8kHz */
937         }
938
939         if (stop) {
940                 blen += strlen(stop);
941         }
942         if (suspend) {
943                 blen += strlen(suspend);
944         }
945         if (restart) {
946                 blen += strlen(restart);
947         }
948
949         if (blen > 2) {
950                 breaks = ast_alloca(blen + 1);
951                 breaks[0] = '\0';
952                 if (stop) {
953                         strcat(breaks, stop);
954                 }
955                 if (suspend) {
956                         strcat(breaks, suspend);
957                 }
958                 if (restart) {
959                         strcat(breaks, restart);
960                 }
961         }
962         if (ast_channel_state(chan) != AST_STATE_UP) {
963                 res = ast_answer(chan);
964         }
965
966         if ((end = strchr(file, ':'))) {
967                 if (!strcasecmp(end, ":end")) {
968                         *end = '\0';
969                         end++;
970                 }
971         }
972
973         for (;;) {
974                 ast_stopstream(chan);
975                 res = ast_streamfile(chan, file, ast_channel_language(chan));
976                 if (!res) {
977                         if (pause_restart_point) {
978                                 ast_seekstream(ast_channel_stream(chan), pause_restart_point, SEEK_SET);
979                                 pause_restart_point = 0;
980                         }
981                         else if (end || offset < 0) {
982                                 if (offset == -8) {
983                                         offset = 0;
984                                 }
985                                 ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
986
987                                 ast_seekstream(ast_channel_stream(chan), offset, SEEK_END);
988                                 end = NULL;
989                                 offset = 0;
990                         } else if (offset) {
991                                 ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
992                                 ast_seekstream(ast_channel_stream(chan), offset, SEEK_SET);
993                                 offset = 0;
994                         }
995                         if (cb) {
996                                 res = ast_waitstream_fr_w_cb(chan, breaks, fwd, rev, skipms, cb);
997                         } else {
998                                 res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
999                         }
1000                 }
1001
1002                 if (res < 1) {
1003                         break;
1004                 }
1005
1006                 /* We go at next loop if we got the restart char */
1007                 if (restart && strchr(restart, res)) {
1008                         ast_debug(1, "we'll restart the stream here at next loop\n");
1009                         pause_restart_point = 0;
1010                         continue;
1011                 }
1012
1013                 if (suspend && strchr(suspend, res)) {
1014                         pause_restart_point = ast_tellstream(ast_channel_stream(chan));
1015                         for (;;) {
1016                                 ast_stopstream(chan);
1017                                 if (!(res = ast_waitfordigit(chan, 1000))) {
1018                                         continue;
1019                                 } else if (res == -1 || strchr(suspend, res) || (stop && strchr(stop, res))) {
1020                                         break;
1021                                 }
1022                         }
1023                         if (res == *suspend) {
1024                                 res = 0;
1025                                 continue;
1026                         }
1027                 }
1028
1029                 if (res == -1) {
1030                         break;
1031                 }
1032
1033                 /* if we get one of our stop chars, return it to the calling function */
1034                 if (stop && strchr(stop, res)) {
1035                         break;
1036                 }
1037         }
1038
1039         if (pause_restart_point) {
1040                 offset = pause_restart_point;
1041         } else {
1042                 if (ast_channel_stream(chan)) {
1043                         offset = ast_tellstream(ast_channel_stream(chan));
1044                 } else {
1045                         offset = -8;  /* indicate end of file */
1046                 }
1047         }
1048
1049         if (offsetms) {
1050                 *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
1051         }
1052
1053         /* If we are returning a digit cast it as char */
1054         if (res > 0 || ast_channel_stream(chan)) {
1055                 res = (char)res;
1056         }
1057
1058         ast_stopstream(chan);
1059
1060         return res;
1061 }
1062
1063 int ast_control_streamfile_w_cb(struct ast_channel *chan,
1064         const char *file,
1065         const char *fwd,
1066         const char *rev,
1067         const char *stop,
1068         const char *suspend,
1069         const char *restart,
1070         int skipms,
1071         long *offsetms,
1072         ast_waitstream_fr_cb cb)
1073 {
1074         return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, cb);
1075 }
1076
1077 int ast_control_streamfile(struct ast_channel *chan, const char *file,
1078                            const char *fwd, const char *rev,
1079                            const char *stop, const char *suspend,
1080                            const char *restart, int skipms, long *offsetms)
1081 {
1082         return control_streamfile(chan, file, fwd, rev, stop, suspend, restart, skipms, offsetms, NULL);
1083 }
1084
1085 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
1086 {
1087         int d = 0;
1088
1089         ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", fn, ast_channel_name(chan));
1090         if ((d = ast_streamfile(chan, fn, ast_channel_language(chan)))) {
1091                 return d;
1092         }
1093
1094         d = ast_waitstream(chan, AST_DIGIT_ANY);
1095
1096         ast_stopstream(chan);
1097
1098         return d;
1099 }
1100
1101 static int global_silence_threshold = 128;
1102 static int global_maxsilence = 0;
1103
1104 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
1105  * \param chan Channel to playback to/record from.
1106  * \param playfile Filename of sound to play before recording begins.
1107  * \param recordfile Filename to record to.
1108  * \param maxtime Maximum length of recording (in seconds).
1109  * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
1110  * \param duration Where to store actual length of the recorded message (in milliseconds).
1111  * \param sound_duration Where to store the length of the recorded message (in milliseconds), minus any silence
1112  * \param beep Whether to play a beep before starting to record.
1113  * \param silencethreshold
1114  * \param maxsilence Length of silence that will end a recording (in milliseconds).
1115  * \param path Optional filesystem path to unlock.
1116  * \param prepend If true, prepend the recorded audio to an existing file and follow prepend mode recording rules
1117  * \param acceptdtmf DTMF digits that will end the recording.
1118  * \param canceldtmf DTMF digits that will cancel the recording.
1119  * \param skip_confirmation_sound If true, don't play auth-thankyou at end. Nice for custom recording prompts in apps.
1120  *
1121  * \retval -1 failure or hangup
1122  * \retval 'S' Recording ended from silence timeout
1123  * \retval 't' Recording ended from the message exceeding the maximum duration, or via DTMF in prepend mode
1124  * \retval dtmfchar Recording ended via the return value's DTMF character for either cancel or accept.
1125  */
1126 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)
1127 {
1128         int d = 0;
1129         char *fmts;
1130         char comment[256];
1131         int x, fmtcnt = 1, res = -1, outmsg = 0;
1132         struct ast_filestream *others[AST_MAX_FORMATS];
1133         char *sfmt[AST_MAX_FORMATS];
1134         char *stringp = NULL;
1135         time_t start, end;
1136         struct ast_dsp *sildet = NULL;   /* silence detector dsp */
1137         int totalsilence = 0;
1138         int dspsilence = 0;
1139         int olddspsilence = 0;
1140         struct ast_format rfmt;
1141         struct ast_silence_generator *silgen = NULL;
1142         char prependfile[PATH_MAX];
1143
1144         ast_format_clear(&rfmt);
1145         if (silencethreshold < 0) {
1146                 silencethreshold = global_silence_threshold;
1147         }
1148
1149         if (maxsilence < 0) {
1150                 maxsilence = global_maxsilence;
1151         }
1152
1153         /* barf if no pointer passed to store duration in */
1154         if (!duration) {
1155                 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
1156                 return -1;
1157         }
1158
1159         ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
1160         snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, ast_channel_name(chan));
1161
1162         if (playfile || beep) {
1163                 if (!beep) {
1164                         d = ast_play_and_wait(chan, playfile);
1165                 }
1166                 if (d > -1) {
1167                         d = ast_stream_and_wait(chan, "beep", "");
1168                 }
1169                 if (d < 0) {
1170                         return -1;
1171                 }
1172         }
1173
1174         if (prepend) {
1175                 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
1176                 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
1177         }
1178
1179         fmts = ast_strdupa(fmt);
1180
1181         stringp = fmts;
1182         strsep(&stringp, "|");
1183         ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
1184         sfmt[0] = ast_strdupa(fmts);
1185
1186         while ((fmt = strsep(&stringp, "|"))) {
1187                 if (fmtcnt > AST_MAX_FORMATS - 1) {
1188                         ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
1189                         break;
1190                 }
1191                 sfmt[fmtcnt++] = ast_strdupa(fmt);
1192         }
1193
1194         end = start = time(NULL);  /* pre-initialize end to be same as start in case we never get into loop */
1195         for (x = 0; x < fmtcnt; x++) {
1196                 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, AST_FILE_MODE);
1197                 ast_verb(3, "x=%d, open writing:  %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
1198
1199                 if (!others[x]) {
1200                         break;
1201                 }
1202         }
1203
1204         if (path) {
1205                 ast_unlock_path(path);
1206         }
1207
1208         if (maxsilence > 0) {
1209                 sildet = ast_dsp_new(); /* Create the silence detector */
1210                 if (!sildet) {
1211                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
1212                         return -1;
1213                 }
1214                 ast_dsp_set_threshold(sildet, silencethreshold);
1215                 ast_format_copy(&rfmt, ast_channel_readformat(chan));
1216                 res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
1217                 if (res < 0) {
1218                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
1219                         ast_dsp_free(sildet);
1220                         return -1;
1221                 }
1222         }
1223
1224         if (!prepend) {
1225                 /* Request a video update */
1226                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
1227
1228                 if (ast_opt_transmit_silence) {
1229                         silgen = ast_channel_start_silence_generator(chan);
1230                 }
1231         }
1232
1233         if (x == fmtcnt) {
1234                 /* Loop forever, writing the packets we read to the writer(s), until
1235                    we read a digit or get a hangup */
1236                 struct ast_frame *f;
1237                 for (;;) {
1238                         if (!(res = ast_waitfor(chan, 2000))) {
1239                                 ast_debug(1, "One waitfor failed, trying another\n");
1240                                 /* Try one more time in case of masq */
1241                                 if (!(res = ast_waitfor(chan, 2000))) {
1242                                         ast_log(LOG_WARNING, "No audio available on %s??\n", ast_channel_name(chan));
1243                                         res = -1;
1244                                 }
1245                         }
1246
1247                         if (res < 0) {
1248                                 f = NULL;
1249                                 break;
1250                         }
1251                         if (!(f = ast_read(chan))) {
1252                                 break;
1253                         }
1254                         if (f->frametype == AST_FRAME_VOICE) {
1255                                 /* write each format */
1256                                 for (x = 0; x < fmtcnt; x++) {
1257                                         if (prepend && !others[x]) {
1258                                                 break;
1259                                         }
1260                                         res = ast_writestream(others[x], f);
1261                                 }
1262
1263                                 /* Silence Detection */
1264                                 if (maxsilence > 0) {
1265                                         dspsilence = 0;
1266                                         ast_dsp_silence(sildet, f, &dspsilence);
1267                                         if (olddspsilence > dspsilence) {
1268                                                 totalsilence += olddspsilence;
1269                                         }
1270                                         olddspsilence = dspsilence;
1271
1272                                         if (dspsilence > maxsilence) {
1273                                                 /* Ended happily with silence */
1274                                                 ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
1275                                                 res = 'S';
1276                                                 outmsg = 2;
1277                                                 break;
1278                                         }
1279                                 }
1280                                 /* Exit on any error */
1281                                 if (res) {
1282                                         ast_log(LOG_WARNING, "Error writing frame\n");
1283                                         break;
1284                                 }
1285                         } else if (f->frametype == AST_FRAME_VIDEO) {
1286                                 /* Write only once */
1287                                 ast_writestream(others[0], f);
1288                         } else if (f->frametype == AST_FRAME_DTMF) {
1289                                 if (prepend) {
1290                                 /* stop recording with any digit */
1291                                         ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1292                                         res = 't';
1293                                         outmsg = 2;
1294                                         break;
1295                                 }
1296                                 if (strchr(acceptdtmf, f->subclass.integer)) {
1297                                         ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
1298                                         res = f->subclass.integer;
1299                                         outmsg = 2;
1300                                         break;
1301                                 }
1302                                 if (strchr(canceldtmf, f->subclass.integer)) {
1303                                         ast_verb(3, "User cancelled message by pressing %c\n", f->subclass.integer);
1304                                         res = f->subclass.integer;
1305                                         outmsg = 0;
1306                                         break;
1307                                 }
1308                         }
1309                         if (maxtime) {
1310                                 end = time(NULL);
1311                                 if (maxtime < (end - start)) {
1312                                         ast_verb(3, "Took too long, cutting it short...\n");
1313                                         res = 't';
1314                                         outmsg = 2;
1315                                         break;
1316                                 }
1317                         }
1318                         ast_frfree(f);
1319                 }
1320                 if (!f) {
1321                         ast_verb(3, "User hung up\n");
1322                         res = -1;
1323                         outmsg = 1;
1324                 } else {
1325                         ast_frfree(f);
1326                 }
1327         } else {
1328                 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
1329         }
1330
1331         if (!prepend) {
1332                 if (silgen) {
1333                         ast_channel_stop_silence_generator(chan, silgen);
1334                 }
1335         }
1336
1337         /*!\note
1338          * Instead of asking how much time passed (end - start), calculate the number
1339          * of seconds of audio which actually went into the file.  This fixes a
1340          * problem where audio is stopped up on the network and never gets to us.
1341          *
1342          * Note that we still want to use the number of seconds passed for the max
1343          * message, otherwise we could get a situation where this stream is never
1344          * closed (which would create a resource leak).
1345          */
1346         *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
1347         if (sound_duration) {
1348                 *sound_duration = *duration;
1349         }
1350
1351         if (!prepend) {
1352                 /* Reduce duration by a total silence amount */
1353                 if (olddspsilence <= dspsilence) {
1354                         totalsilence += dspsilence;
1355                 }
1356
1357                 if (sound_duration) {
1358                         if (totalsilence > 0) {
1359                                 *sound_duration -= (totalsilence - 200) / 1000;
1360                         }
1361                         if (*sound_duration < 0) {
1362                                 *sound_duration = 0;
1363                         }
1364                 }
1365
1366                 if (dspsilence > 0) {
1367                         *duration -= (dspsilence - 200) / 1000;
1368                 }
1369
1370                 if (*duration < 0) {
1371                         *duration = 0;
1372                 }
1373
1374                 for (x = 0; x < fmtcnt; x++) {
1375                         if (!others[x]) {
1376                                 break;
1377                         }
1378                         /*!\note
1379                          * If we ended with silence, trim all but the first 200ms of silence
1380                          * off the recording.  However, if we ended with '#', we don't want
1381                          * to trim ANY part of the recording.
1382                          */
1383                         if (res > 0 && dspsilence) {
1384                                 /* rewind only the trailing silence */
1385                                 ast_stream_rewind(others[x], dspsilence - 200);
1386                         }
1387                         ast_truncstream(others[x]);
1388                         ast_closestream(others[x]);
1389                 }
1390         }
1391
1392         if (prepend && outmsg) {
1393                 struct ast_filestream *realfiles[AST_MAX_FORMATS];
1394                 struct ast_frame *fr;
1395
1396                 for (x = 0; x < fmtcnt; x++) {
1397                         snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
1398                         realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
1399                         if (!others[x] || !realfiles[x]) {
1400                                 break;
1401                         }
1402                         /*!\note Same logic as above. */
1403                         if (dspsilence) {
1404                                 ast_stream_rewind(others[x], dspsilence - 200);
1405                         }
1406                         ast_truncstream(others[x]);
1407                         /* add the original file too */
1408                         while ((fr = ast_readframe(realfiles[x]))) {
1409                                 ast_writestream(others[x], fr);
1410                                 ast_frfree(fr);
1411                         }
1412                         ast_closestream(others[x]);
1413                         ast_closestream(realfiles[x]);
1414                         ast_filerename(prependfile, recordfile, sfmt[x]);
1415                         ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
1416                         ast_filedelete(prependfile, sfmt[x]);
1417                 }
1418         }
1419         if (rfmt.id && ast_set_read_format(chan, &rfmt)) {
1420                 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(&rfmt), ast_channel_name(chan));
1421         }
1422         if ((outmsg == 2) && (!skip_confirmation_sound)) {
1423                 ast_stream_and_wait(chan, "auth-thankyou", "");
1424         }
1425         if (sildet) {
1426                 ast_dsp_free(sildet);
1427         }
1428         return res;
1429 }
1430
1431 static const char default_acceptdtmf[] = "#";
1432 static const char default_canceldtmf[] = "";
1433
1434 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 silencethreshold, int maxsilence, const char *path, const char *acceptdtmf, const char *canceldtmf)
1435 {
1436         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, S_OR(acceptdtmf, default_acceptdtmf), S_OR(canceldtmf, default_canceldtmf), 0);
1437 }
1438
1439 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)
1440 {
1441         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf, 0);
1442 }
1443
1444 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)
1445 {
1446         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf, 1);
1447 }
1448
1449 /* Channel group core functions */
1450
1451 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
1452 {
1453         int res = 0;
1454         char tmp[256];
1455         char *grp = NULL, *cat = NULL;
1456
1457         if (!ast_strlen_zero(data)) {
1458                 ast_copy_string(tmp, data, sizeof(tmp));
1459                 grp = tmp;
1460                 if ((cat = strchr(tmp, '@'))) {
1461                         *cat++ = '\0';
1462                 }
1463         }
1464
1465         if (!ast_strlen_zero(grp)) {
1466                 ast_copy_string(group, grp, group_max);
1467         } else {
1468                 *group = '\0';
1469         }
1470
1471         if (!ast_strlen_zero(cat)) {
1472                 ast_copy_string(category, cat, category_max);
1473         }
1474
1475         return res;
1476 }
1477
1478 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
1479 {
1480         int res = 0;
1481         char group[80] = "", category[80] = "";
1482         struct ast_group_info *gi = NULL;
1483         size_t len = 0;
1484
1485         if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
1486                 return -1;
1487         }
1488
1489         /* Calculate memory we will need if this is new */
1490         len = sizeof(*gi) + strlen(group) + 1;
1491         if (!ast_strlen_zero(category)) {
1492                 len += strlen(category) + 1;
1493         }
1494
1495         AST_RWLIST_WRLOCK(&groups);
1496         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1497                 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1498                         AST_RWLIST_REMOVE_CURRENT(group_list);
1499                         free(gi);
1500                         break;
1501                 }
1502         }
1503         AST_RWLIST_TRAVERSE_SAFE_END;
1504
1505         if (ast_strlen_zero(group)) {
1506                 /* Enable unsetting the group */
1507         } else if ((gi = calloc(1, len))) {
1508                 gi->chan = chan;
1509                 gi->group = (char *) gi + sizeof(*gi);
1510                 strcpy(gi->group, group);
1511                 if (!ast_strlen_zero(category)) {
1512                         gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
1513                         strcpy(gi->category, category);
1514                 }
1515                 AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
1516         } else {
1517                 res = -1;
1518         }
1519
1520         AST_RWLIST_UNLOCK(&groups);
1521
1522         return res;
1523 }
1524
1525 int ast_app_group_get_count(const char *group, const char *category)
1526 {
1527         struct ast_group_info *gi = NULL;
1528         int count = 0;
1529
1530         if (ast_strlen_zero(group)) {
1531                 return 0;
1532         }
1533
1534         AST_RWLIST_RDLOCK(&groups);
1535         AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1536                 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1537                         count++;
1538                 }
1539         }
1540         AST_RWLIST_UNLOCK(&groups);
1541
1542         return count;
1543 }
1544
1545 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
1546 {
1547         struct ast_group_info *gi = NULL;
1548         regex_t regexbuf_group;
1549         regex_t regexbuf_category;
1550         int count = 0;
1551
1552         if (ast_strlen_zero(groupmatch)) {
1553                 ast_log(LOG_NOTICE, "groupmatch empty\n");
1554                 return 0;
1555         }
1556
1557         /* if regex compilation fails, return zero matches */
1558         if (regcomp(&regexbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
1559                 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
1560                 return 0;
1561         }
1562
1563         if (!ast_strlen_zero(category) && regcomp(&regexbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
1564                 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
1565                 return 0;
1566         }
1567
1568         AST_RWLIST_RDLOCK(&groups);
1569         AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1570                 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)))) {
1571                         count++;
1572                 }
1573         }
1574         AST_RWLIST_UNLOCK(&groups);
1575
1576         regfree(&regexbuf_group);
1577         if (!ast_strlen_zero(category)) {
1578                 regfree(&regexbuf_category);
1579         }
1580
1581         return count;
1582 }
1583
1584 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
1585 {
1586         struct ast_group_info *gi = NULL;
1587
1588         AST_RWLIST_WRLOCK(&groups);
1589         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1590                 if (gi->chan == old) {
1591                         gi->chan = new;
1592                 } else if (gi->chan == new) {
1593                         AST_RWLIST_REMOVE_CURRENT(group_list);
1594                         ast_free(gi);
1595                 }
1596         }
1597         AST_RWLIST_TRAVERSE_SAFE_END;
1598         AST_RWLIST_UNLOCK(&groups);
1599
1600         return 0;
1601 }
1602
1603 int ast_app_group_discard(struct ast_channel *chan)
1604 {
1605         struct ast_group_info *gi = NULL;
1606
1607         AST_RWLIST_WRLOCK(&groups);
1608         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1609                 if (gi->chan == chan) {
1610                         AST_RWLIST_REMOVE_CURRENT(group_list);
1611                         ast_free(gi);
1612                 }
1613         }
1614         AST_RWLIST_TRAVERSE_SAFE_END;
1615         AST_RWLIST_UNLOCK(&groups);
1616
1617         return 0;
1618 }
1619
1620 int ast_app_group_list_wrlock(void)
1621 {
1622         return AST_RWLIST_WRLOCK(&groups);
1623 }
1624
1625 int ast_app_group_list_rdlock(void)
1626 {
1627         return AST_RWLIST_RDLOCK(&groups);
1628 }
1629
1630 struct ast_group_info *ast_app_group_list_head(void)
1631 {
1632         return AST_RWLIST_FIRST(&groups);
1633 }
1634
1635 int ast_app_group_list_unlock(void)
1636 {
1637         return AST_RWLIST_UNLOCK(&groups);
1638 }
1639
1640 #undef ast_app_separate_args
1641 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
1642
1643 unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
1644 {
1645         int argc;
1646         char *scan, *wasdelim = NULL;
1647         int paren = 0, quote = 0, bracket = 0;
1648
1649         if (!array || !arraylen) {
1650                 return 0;
1651         }
1652
1653         memset(array, 0, arraylen * sizeof(*array));
1654
1655         if (!buf) {
1656                 return 0;
1657         }
1658
1659         scan = buf;
1660
1661         for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
1662                 array[argc] = scan;
1663                 for (; *scan; scan++) {
1664                         if (*scan == '(') {
1665                                 paren++;
1666                         } else if (*scan == ')') {
1667                                 if (paren) {
1668                                         paren--;
1669                                 }
1670                         } else if (*scan == '[') {
1671                                 bracket++;
1672                         } else if (*scan == ']') {
1673                                 if (bracket) {
1674                                         bracket--;
1675                                 }
1676                         } else if (*scan == '"' && delim != '"') {
1677                                 quote = quote ? 0 : 1;
1678                                 if (remove_chars) {
1679                                         /* Remove quote character from argument */
1680                                         memmove(scan, scan + 1, strlen(scan));
1681                                         scan--;
1682                                 }
1683                         } else if (*scan == '\\') {
1684                                 if (remove_chars) {
1685                                         /* Literal character, don't parse */
1686                                         memmove(scan, scan + 1, strlen(scan));
1687                                 } else {
1688                                         scan++;
1689                                 }
1690                         } else if ((*scan == delim) && !paren && !quote && !bracket) {
1691                                 wasdelim = scan;
1692                                 *scan++ = '\0';
1693                                 break;
1694                         }
1695                 }
1696         }
1697
1698         /* If the last character in the original string was the delimiter, then
1699          * there is one additional argument. */
1700         if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
1701                 array[argc++] = scan;
1702         }
1703
1704         return argc;
1705 }
1706
1707 /* ABI compatible function */
1708 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
1709 {
1710         return __ast_app_separate_args(buf, delim, 1, array, arraylen);
1711 }
1712
1713 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
1714 {
1715         char *s;
1716         char *fs;
1717         int res;
1718         int fd;
1719         int lp = strlen(path);
1720         time_t start;
1721
1722         s = ast_alloca(lp + 10);
1723         fs = ast_alloca(lp + 20);
1724
1725         snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
1726         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
1727         if (fd < 0) {
1728                 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
1729                 return AST_LOCK_PATH_NOT_FOUND;
1730         }
1731         close(fd);
1732
1733         snprintf(s, strlen(path) + 9, "%s/.lock", path);
1734         start = time(NULL);
1735         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
1736                 sched_yield();
1737         }
1738
1739         unlink(fs);
1740
1741         if (res) {
1742                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1743                 return AST_LOCK_TIMEOUT;
1744         } else {
1745                 ast_debug(1, "Locked path '%s'\n", path);
1746                 return AST_LOCK_SUCCESS;
1747         }
1748 }
1749
1750 static int ast_unlock_path_lockfile(const char *path)
1751 {
1752         char *s;
1753         int res;
1754
1755         s = ast_alloca(strlen(path) + 10);
1756
1757         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1758
1759         if ((res = unlink(s))) {
1760                 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
1761         } else {
1762                 ast_debug(1, "Unlocked path '%s'\n", path);
1763         }
1764
1765         return res;
1766 }
1767
1768 struct path_lock {
1769         AST_LIST_ENTRY(path_lock) le;
1770         int fd;
1771         char *path;
1772 };
1773
1774 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
1775
1776 static void path_lock_destroy(struct path_lock *obj)
1777 {
1778         if (obj->fd >= 0) {
1779                 close(obj->fd);
1780         }
1781         if (obj->path) {
1782                 free(obj->path);
1783         }
1784         free(obj);
1785 }
1786
1787 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
1788 {
1789         char *fs;
1790         int res;
1791         int fd;
1792         time_t start;
1793         struct path_lock *pl;
1794         struct stat st, ost;
1795
1796         fs = ast_alloca(strlen(path) + 20);
1797
1798         snprintf(fs, strlen(path) + 19, "%s/lock", path);
1799         if (lstat(fs, &st) == 0) {
1800                 if ((st.st_mode & S_IFMT) == S_IFLNK) {
1801                         ast_log(LOG_WARNING, "Unable to create lock file "
1802                                         "'%s': it's already a symbolic link\n",
1803                                         fs);
1804                         return AST_LOCK_FAILURE;
1805                 }
1806                 if (st.st_nlink > 1) {
1807                         ast_log(LOG_WARNING, "Unable to create lock file "
1808                                         "'%s': %u hard links exist\n",
1809                                         fs, (unsigned int) st.st_nlink);
1810                         return AST_LOCK_FAILURE;
1811                 }
1812         }
1813         if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
1814                 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
1815                                 fs, strerror(errno));
1816                 return AST_LOCK_PATH_NOT_FOUND;
1817         }
1818         if (!(pl = ast_calloc(1, sizeof(*pl)))) {
1819                 /* We don't unlink the lock file here, on the possibility that
1820                  * someone else created it - better to leave a little mess
1821                  * than create a big one by destroying someone else's lock
1822                  * and causing something to be corrupted.
1823                  */
1824                 close(fd);
1825                 return AST_LOCK_FAILURE;
1826         }
1827         pl->fd = fd;
1828         pl->path = strdup(path);
1829
1830         time(&start);
1831         while (
1832                 #ifdef SOLARIS
1833                 ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
1834                 #else
1835                 ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
1836                 #endif
1837                         (errno == EWOULDBLOCK) &&
1838                         (time(NULL) - start < 5))
1839                 usleep(1000);
1840         if (res) {
1841                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
1842                                 path, strerror(errno));
1843                 /* No unlinking of lock done, since we tried and failed to
1844                  * flock() it.
1845                  */
1846                 path_lock_destroy(pl);
1847                 return AST_LOCK_TIMEOUT;
1848         }
1849
1850         /* Check for the race where the file is recreated or deleted out from
1851          * underneath us.
1852          */
1853         if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
1854                         st.st_dev != ost.st_dev &&
1855                         st.st_ino != ost.st_ino) {
1856                 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
1857                                 "file changed underneath us\n", fs);
1858                 path_lock_destroy(pl);
1859                 return AST_LOCK_FAILURE;
1860         }
1861
1862         /* Success: file created, flocked, and is the one we started with */
1863         AST_LIST_LOCK(&path_lock_list);
1864         AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
1865         AST_LIST_UNLOCK(&path_lock_list);
1866
1867         ast_debug(1, "Locked path '%s'\n", path);
1868
1869         return AST_LOCK_SUCCESS;
1870 }
1871
1872 static int ast_unlock_path_flock(const char *path)
1873 {
1874         char *s;
1875         struct path_lock *p;
1876
1877         s = ast_alloca(strlen(path) + 20);
1878
1879         AST_LIST_LOCK(&path_lock_list);
1880         AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
1881                 if (!strcmp(p->path, path)) {
1882                         AST_LIST_REMOVE_CURRENT(le);
1883                         break;
1884                 }
1885         }
1886         AST_LIST_TRAVERSE_SAFE_END;
1887         AST_LIST_UNLOCK(&path_lock_list);
1888
1889         if (p) {
1890                 snprintf(s, strlen(path) + 19, "%s/lock", path);
1891                 unlink(s);
1892                 path_lock_destroy(p);
1893                 ast_debug(1, "Unlocked path '%s'\n", path);
1894         } else {
1895                 ast_debug(1, "Failed to unlock path '%s': "
1896                                 "lock not found\n", path);
1897         }
1898
1899         return 0;
1900 }
1901
1902 void ast_set_lock_type(enum AST_LOCK_TYPE type)
1903 {
1904         ast_lock_type = type;
1905 }
1906
1907 enum AST_LOCK_RESULT ast_lock_path(const char *path)
1908 {
1909         enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
1910
1911         switch (ast_lock_type) {
1912         case AST_LOCK_TYPE_LOCKFILE:
1913                 r = ast_lock_path_lockfile(path);
1914                 break;
1915         case AST_LOCK_TYPE_FLOCK:
1916                 r = ast_lock_path_flock(path);
1917                 break;
1918         }
1919
1920         return r;
1921 }
1922
1923 int ast_unlock_path(const char *path)
1924 {
1925         int r = 0;
1926
1927         switch (ast_lock_type) {
1928         case AST_LOCK_TYPE_LOCKFILE:
1929                 r = ast_unlock_path_lockfile(path);
1930                 break;
1931         case AST_LOCK_TYPE_FLOCK:
1932                 r = ast_unlock_path_flock(path);
1933                 break;
1934         }
1935
1936         return r;
1937 }
1938
1939 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
1940 {
1941         int silencethreshold;
1942         int maxsilence = 0;
1943         int res = 0;
1944         int cmd = 0;
1945         int max_attempts = 3;
1946         int attempts = 0;
1947         int recorded = 0;
1948         int message_exists = 0;
1949         /* Note that urgent and private are for flagging messages as such in the future */
1950
1951         /* barf if no pointer passed to store duration in */
1952         if (!duration) {
1953                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1954                 return -1;
1955         }
1956
1957         cmd = '3';       /* Want to start by recording */
1958
1959         silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
1960
1961         while ((cmd >= 0) && (cmd != 't')) {
1962                 switch (cmd) {
1963                 case '1':
1964                         if (!message_exists) {
1965                                 /* In this case, 1 is to record a message */
1966                                 cmd = '3';
1967                                 break;
1968                         } else {
1969                                 ast_stream_and_wait(chan, "vm-msgsaved", "");
1970                                 cmd = 't';
1971                                 return res;
1972                         }
1973                 case '2':
1974                         /* Review */
1975                         ast_verb(3, "Reviewing the recording\n");
1976                         cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
1977                         break;
1978                 case '3':
1979                         message_exists = 0;
1980                         /* Record */
1981                         ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
1982                         recorded = 1;
1983                         if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
1984                                 /* User has hung up, no options to give */
1985                                 return cmd;
1986                         }
1987                         if (cmd == '0') {
1988                                 break;
1989                         } else if (cmd == '*') {
1990                                 break;
1991                         } else {
1992                                 /* If all is well, a message exists */
1993                                 message_exists = 1;
1994                                 cmd = 0;
1995                         }
1996                         break;
1997                 case '4':
1998                 case '5':
1999                 case '6':
2000                 case '7':
2001                 case '8':
2002                 case '9':
2003                 case '*':
2004                 case '#':
2005                         cmd = ast_play_and_wait(chan, "vm-sorry");
2006                         break;
2007                 default:
2008                         if (message_exists) {
2009                                 cmd = ast_play_and_wait(chan, "vm-review");
2010                         } else {
2011                                 if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
2012                                         cmd = ast_waitfordigit(chan, 600);
2013                                 }
2014                         }
2015
2016                         if (!cmd) {
2017                                 cmd = ast_waitfordigit(chan, 6000);
2018                         }
2019                         if (!cmd) {
2020                                 attempts++;
2021                         }
2022                         if (attempts > max_attempts) {
2023                                 cmd = 't';
2024                         }
2025                 }
2026         }
2027         if (cmd == 't') {
2028                 cmd = 0;
2029         }
2030         return cmd;
2031 }
2032
2033 #define RES_UPONE (1 << 16)
2034 #define RES_EXIT  (1 << 17)
2035 #define RES_REPEAT (1 << 18)
2036 #define RES_RESTART ((1 << 19) | RES_REPEAT)
2037
2038 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
2039
2040 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
2041 {
2042         int res;
2043         int (*ivr_func)(struct ast_channel *, void *);
2044         char *c;
2045         char *n;
2046
2047         switch (option->action) {
2048         case AST_ACTION_UPONE:
2049                 return RES_UPONE;
2050         case AST_ACTION_EXIT:
2051                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
2052         case AST_ACTION_REPEAT:
2053                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
2054         case AST_ACTION_RESTART:
2055                 return RES_RESTART ;
2056         case AST_ACTION_NOOP:
2057                 return 0;
2058         case AST_ACTION_BACKGROUND:
2059                 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
2060                 if (res < 0) {
2061                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2062                         res = 0;
2063                 }
2064                 return res;
2065         case AST_ACTION_PLAYBACK:
2066                 res = ast_stream_and_wait(chan, (char *)option->adata, "");
2067                 if (res < 0) {
2068                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2069                         res = 0;
2070                 }
2071                 return res;
2072         case AST_ACTION_MENU:
2073                 if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
2074                         /* Do not pass entry errors back up, treat as though it was an "UPONE" */
2075                         res = 0;
2076                 }
2077                 return res;
2078         case AST_ACTION_WAITOPTION:
2079                 if (!(res = ast_waitfordigit(chan, ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000))) {
2080                         return 't';
2081                 }
2082                 return res;
2083         case AST_ACTION_CALLBACK:
2084                 ivr_func = option->adata;
2085                 res = ivr_func(chan, cbdata);
2086                 return res;
2087         case AST_ACTION_TRANSFER:
2088                 res = ast_parseable_goto(chan, option->adata);
2089                 return 0;
2090         case AST_ACTION_PLAYLIST:
2091         case AST_ACTION_BACKLIST:
2092                 res = 0;
2093                 c = ast_strdupa(option->adata);
2094                 while ((n = strsep(&c, ";"))) {
2095                         if ((res = ast_stream_and_wait(chan, n,
2096                                         (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
2097                                 break;
2098                         }
2099                 }
2100                 ast_stopstream(chan);
2101                 return res;
2102         default:
2103                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
2104                 return 0;
2105         }
2106         return -1;
2107 }
2108
2109 static int option_exists(struct ast_ivr_menu *menu, char *option)
2110 {
2111         int x;
2112         for (x = 0; menu->options[x].option; x++) {
2113                 if (!strcasecmp(menu->options[x].option, option)) {
2114                         return x;
2115                 }
2116         }
2117         return -1;
2118 }
2119
2120 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
2121 {
2122         int x;
2123         for (x = 0; menu->options[x].option; x++) {
2124                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
2125                                 (menu->options[x].option[strlen(option)])) {
2126                         return x;
2127                 }
2128         }
2129         return -1;
2130 }
2131
2132 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
2133 {
2134         int res = 0;
2135         int ms;
2136         while (option_matchmore(menu, exten)) {
2137                 ms = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
2138                 if (strlen(exten) >= maxexten - 1) {
2139                         break;
2140                 }
2141                 if ((res = ast_waitfordigit(chan, ms)) < 1) {
2142                         break;
2143                 }
2144                 exten[strlen(exten) + 1] = '\0';
2145                 exten[strlen(exten)] = res;
2146         }
2147         return res > 0 ? 0 : res;
2148 }
2149
2150 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2151 {
2152         /* Execute an IVR menu structure */
2153         int res = 0;
2154         int pos = 0;
2155         int retries = 0;
2156         char exten[AST_MAX_EXTENSION] = "s";
2157         if (option_exists(menu, "s") < 0) {
2158                 strcpy(exten, "g");
2159                 if (option_exists(menu, "g") < 0) {
2160                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
2161                         return -1;
2162                 }
2163         }
2164         while (!res) {
2165                 while (menu->options[pos].option) {
2166                         if (!strcasecmp(menu->options[pos].option, exten)) {
2167                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
2168                                 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
2169                                 if (res < 0) {
2170                                         break;
2171                                 } else if (res & RES_UPONE) {
2172                                         return 0;
2173                                 } else if (res & RES_EXIT) {
2174                                         return res;
2175                                 } else if (res & RES_REPEAT) {
2176                                         int maxretries = res & 0xffff;
2177                                         if ((res & RES_RESTART) == RES_RESTART) {
2178                                                 retries = 0;
2179                                         } else {
2180                                                 retries++;
2181                                         }
2182                                         if (!maxretries) {
2183                                                 maxretries = 3;
2184                                         }
2185                                         if ((maxretries > 0) && (retries >= maxretries)) {
2186                                                 ast_debug(1, "Max retries %d exceeded\n", maxretries);
2187                                                 return -2;
2188                                         } else {
2189                                                 if (option_exists(menu, "g") > -1) {
2190                                                         strcpy(exten, "g");
2191                                                 } else if (option_exists(menu, "s") > -1) {
2192                                                         strcpy(exten, "s");
2193                                                 }
2194                                         }
2195                                         pos = 0;
2196                                         continue;
2197                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
2198                                         ast_debug(1, "Got start of extension, %c\n", res);
2199                                         exten[1] = '\0';
2200                                         exten[0] = res;
2201                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
2202                                                 break;
2203                                         }
2204                                         if (option_exists(menu, exten) < 0) {
2205                                                 if (option_exists(menu, "i")) {
2206                                                         ast_debug(1, "Invalid extension entered, going to 'i'!\n");
2207                                                         strcpy(exten, "i");
2208                                                         pos = 0;
2209                                                         continue;
2210                                                 } else {
2211                                                         ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
2212                                                         res = -2;
2213                                                         break;
2214                                                 }
2215                                         } else {
2216                                                 ast_debug(1, "New existing extension: %s\n", exten);
2217                                                 pos = 0;
2218                                                 continue;
2219                                         }
2220                                 }
2221                         }
2222                         pos++;
2223                 }
2224                 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
2225                 pos = 0;
2226                 if (!strcasecmp(exten, "s")) {
2227                         strcpy(exten, "g");
2228                 } else {
2229                         break;
2230                 }
2231         }
2232         return res;
2233 }
2234
2235 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2236 {
2237         int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
2238         /* Hide internal coding */
2239         return res > 0 ? 0 : res;
2240 }
2241
2242 char *ast_read_textfile(const char *filename)
2243 {
2244         int fd, count = 0, res;
2245         char *output = NULL;
2246         struct stat filesize;
2247
2248         if (stat(filename, &filesize) == -1) {
2249                 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
2250                 return NULL;
2251         }
2252
2253         count = filesize.st_size + 1;
2254
2255         if ((fd = open(filename, O_RDONLY)) < 0) {
2256                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
2257                 return NULL;
2258         }
2259
2260         if ((output = ast_malloc(count))) {
2261                 res = read(fd, output, count - 1);
2262                 if (res == count - 1) {
2263                         output[res] = '\0';
2264                 } else {
2265                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
2266                         ast_free(output);
2267                         output = NULL;
2268                 }
2269         }
2270
2271         close(fd);
2272
2273         return output;
2274 }
2275
2276 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
2277 {
2278         char *s, *arg;
2279         int curarg, res = 0;
2280         unsigned int argloc;
2281         struct ast_flags *flags = _flags;
2282         struct ast_flags64 *flags64 = _flags;
2283
2284         if (flaglen == 32) {
2285                 ast_clear_flag(flags, AST_FLAGS_ALL);
2286         } else {
2287                 flags64->flags = 0;
2288         }
2289
2290         if (!optstr) {
2291                 return 0;
2292         }
2293
2294         s = optstr;
2295         while (*s) {
2296                 curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
2297                 argloc = options[curarg].arg_index;
2298                 if (*s == '(') {
2299                         int paren = 1, quote = 0;
2300                         int parsequotes = (s[1] == '"') ? 1 : 0;
2301
2302                         /* Has argument */
2303                         arg = ++s;
2304                         for (; *s; s++) {
2305                                 if (*s == '(' && !quote) {
2306                                         paren++;
2307                                 } else if (*s == ')' && !quote) {
2308                                         /* Count parentheses, unless they're within quotes (or backslashed, below) */
2309                                         paren--;
2310                                 } else if (*s == '"' && parsequotes) {
2311                                         /* Leave embedded quotes alone, unless they are the first character */
2312                                         quote = quote ? 0 : 1;
2313                                         ast_copy_string(s, s + 1, INT_MAX);
2314                                         s--;
2315                                 } else if (*s == '\\') {
2316                                         if (!quote) {
2317                                                 /* If a backslash is found outside of quotes, remove it */
2318                                                 ast_copy_string(s, s + 1, INT_MAX);
2319                                         } else if (quote && s[1] == '"') {
2320                                                 /* Backslash for a quote character within quotes, remove the backslash */
2321                                                 ast_copy_string(s, s + 1, INT_MAX);
2322                                         } else {
2323                                                 /* Backslash within quotes, keep both characters */
2324                                                 s++;
2325                                         }
2326                                 }
2327
2328                                 if (paren == 0) {
2329                                         break;
2330                                 }
2331                         }
2332                         /* This will find the closing paren we found above, or none, if the string ended before we found one. */
2333                         if ((s = strchr(s, ')'))) {
2334                                 if (argloc) {
2335                                         args[argloc - 1] = arg;
2336                                 }
2337                                 *s++ = '\0';
2338                         } else {
2339                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
2340                                 res = -1;
2341                                 break;
2342                         }
2343                 } else if (argloc) {
2344                         args[argloc - 1] = "";
2345                 }
2346                 if (flaglen == 32) {
2347                         ast_set_flag(flags, options[curarg].flag);
2348                 } else {
2349                         ast_set_flag64(flags64, options[curarg].flag);
2350                 }
2351         }
2352
2353         return res;
2354 }
2355
2356 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
2357 {
2358         return parse_options(options, flags, args, optstr, 32);
2359 }
2360
2361 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
2362 {
2363         return parse_options(options, flags, args, optstr, 64);
2364 }
2365
2366 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
2367 {
2368         unsigned int i, found = 0;
2369         for (i = 32; i < 128 && found < len; i++) {
2370                 if (ast_test_flag64(flags, options[i].flag)) {
2371                         buf[found++] = i;
2372                 }
2373         }
2374         buf[found] = '\0';
2375 }
2376
2377 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
2378 {
2379         int i;
2380         *consumed = 1;
2381         *result = 0;
2382         if (ast_strlen_zero(stream)) {
2383                 *consumed = 0;
2384                 return -1;
2385         }
2386
2387         if (*stream == '\\') {
2388                 *consumed = 2;
2389                 switch (*(stream + 1)) {
2390                 case 'n':
2391                         *result = '\n';
2392                         break;
2393                 case 'r':
2394                         *result = '\r';
2395                         break;
2396                 case 't':
2397                         *result = '\t';
2398                         break;
2399                 case 'x':
2400                         /* Hexadecimal */
2401                         if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
2402                                 *consumed = 3;
2403                                 if (*(stream + 2) <= '9') {
2404                                         *result = *(stream + 2) - '0';
2405                                 } else if (*(stream + 2) <= 'F') {
2406                                         *result = *(stream + 2) - 'A' + 10;
2407                                 } else {
2408                                         *result = *(stream + 2) - 'a' + 10;
2409                                 }
2410                         } else {
2411                                 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
2412                                 return -1;
2413                         }
2414
2415                         if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
2416                                 *consumed = 4;
2417                                 *result <<= 4;
2418                                 if (*(stream + 3) <= '9') {
2419                                         *result += *(stream + 3) - '0';
2420                                 } else if (*(stream + 3) <= 'F') {
2421                                         *result += *(stream + 3) - 'A' + 10;
2422                                 } else {
2423                                         *result += *(stream + 3) - 'a' + 10;
2424                                 }
2425                         }
2426                         break;
2427                 case '0':
2428                         /* Octal */
2429                         *consumed = 2;
2430                         for (i = 2; ; i++) {
2431                                 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
2432                                         (*consumed)++;
2433                                         ast_debug(5, "result was %d, ", *result);
2434                                         *result <<= 3;
2435                                         *result += *(stream + i) - '0';
2436                                         ast_debug(5, "is now %d\n", *result);
2437                                 } else {
2438                                         break;
2439                                 }
2440                         }
2441                         break;
2442                 default:
2443                         *result = *(stream + 1);
2444                 }
2445         } else {
2446                 *result = *stream;
2447                 *consumed = 1;
2448         }
2449         return 0;
2450 }
2451
2452 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
2453 {
2454         char *cur = result;
2455         size_t consumed;
2456
2457         while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
2458                 cur++;
2459                 stream += consumed;
2460         }
2461         *cur = '\0';
2462         return result;
2463 }
2464
2465 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
2466 {
2467         char next, *buf;
2468         size_t offset = 0;
2469         size_t consumed;
2470
2471         if (strchr(stream, '\\')) {
2472                 while (!ast_get_encoded_char(stream, &next, &consumed)) {
2473                         if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
2474                                 ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
2475                         }
2476                         if (offset + 2 > ast_str_size(*str)) {
2477                                 break;
2478                         }
2479                         buf = ast_str_buffer(*str);
2480                         buf[offset++] = next;
2481                         stream += consumed;
2482                 }
2483                 buf = ast_str_buffer(*str);
2484                 buf[offset++] = '\0';
2485                 ast_str_update(*str);
2486         } else {
2487                 ast_str_set(str, maxlen, "%s", stream);
2488         }
2489         return 0;
2490 }
2491
2492 void ast_close_fds_above_n(int n)
2493 {
2494         closefrom(n + 1);
2495 }
2496
2497 int ast_safe_fork(int stop_reaper)
2498 {
2499         sigset_t signal_set, old_set;
2500         int pid;
2501
2502         /* Don't let the default signal handler for children reap our status */
2503         if (stop_reaper) {
2504                 ast_replace_sigchld();
2505         }
2506
2507         sigfillset(&signal_set);
2508         pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
2509
2510         pid = fork();
2511
2512         if (pid != 0) {
2513                 /* Fork failed or parent */
2514                 pthread_sigmask(SIG_SETMASK, &old_set, NULL);
2515                 if (!stop_reaper && pid > 0) {
2516                         struct zombie *cur = ast_calloc(1, sizeof(*cur));
2517                         if (cur) {
2518                                 cur->pid = pid;
2519                                 AST_LIST_LOCK(&zombies);
2520                                 AST_LIST_INSERT_TAIL(&zombies, cur, list);
2521                                 AST_LIST_UNLOCK(&zombies);
2522                                 if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
2523                                         if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
2524                                                 ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
2525                                                 shaun_of_the_dead_thread = AST_PTHREADT_NULL;
2526                                         }
2527                                 }
2528                         }
2529                 }
2530                 return pid;
2531         } else {
2532                 /* Child */
2533 #ifdef HAVE_CAP
2534                 cap_t cap = cap_from_text("cap_net_admin-eip");
2535
2536                 if (cap_set_proc(cap)) {
2537                         ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
2538                 }
2539                 cap_free(cap);
2540 #endif
2541
2542                 /* Before we unblock our signals, return our trapped signals back to the defaults */
2543                 signal(SIGHUP, SIG_DFL);
2544                 signal(SIGCHLD, SIG_DFL);
2545                 signal(SIGINT, SIG_DFL);
2546                 signal(SIGURG, SIG_DFL);
2547                 signal(SIGTERM, SIG_DFL);
2548                 signal(SIGPIPE, SIG_DFL);
2549                 signal(SIGXFSZ, SIG_DFL);
2550
2551                 /* unblock important signal handlers */
2552                 if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
2553                         ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
2554                         _exit(1);
2555                 }
2556
2557                 return pid;
2558         }
2559 }
2560
2561 void ast_safe_fork_cleanup(void)
2562 {
2563         ast_unreplace_sigchld();
2564 }
2565
2566 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
2567 {
2568         int res;
2569         char u[10];
2570 #ifdef HAVE_LONG_DOUBLE_WIDER
2571         long double amount;
2572         #define FMT "%30Lf%9s"
2573 #else
2574         double amount;
2575         #define FMT "%30lf%9s"
2576 #endif
2577         if (!timestr) {
2578                 return -1;
2579         }
2580
2581         if ((res = sscanf(timestr, FMT, &amount, u)) == 0) {
2582 #undef FMT
2583                 return -1;
2584         } else if (res == 2) {
2585                 switch (u[0]) {
2586                 case 'h':
2587                 case 'H':
2588                         unit = TIMELEN_HOURS;
2589                         break;
2590                 case 's':
2591                 case 'S':
2592                         unit = TIMELEN_SECONDS;
2593                         break;
2594                 case 'm':
2595                 case 'M':
2596                         if (toupper(u[1]) == 'S') {
2597                                 unit = TIMELEN_MILLISECONDS;
2598                         } else if (u[1] == '\0') {
2599                                 unit = TIMELEN_MINUTES;
2600                         }
2601                         break;
2602                 }
2603         }
2604
2605         switch (unit) {
2606         case TIMELEN_HOURS:
2607                 amount *= 60;
2608                 /* fall-through */
2609         case TIMELEN_MINUTES:
2610                 amount *= 60;
2611                 /* fall-through */
2612         case TIMELEN_SECONDS:
2613                 amount *= 1000;
2614                 /* fall-through */
2615         case TIMELEN_MILLISECONDS:
2616                 ;
2617         }
2618         *result = amount > INT_MAX ? INT_MAX : (int) amount;
2619         return 0;
2620 }
2621