208db4b838eabea5dfae9253717e110822c9d490
[asterisk/asterisk.git] / main / app.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Convenient Application Routines
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 /** \example
27  * \par This is an example of how to develop an app.
28  * Application Skeleton is an example of creating an application for Asterisk.
29  * \verbinclude app_skel.c
30  */
31
32 /*** MODULEINFO
33         <support_level>core</support_level>
34  ***/
35
36 #include "asterisk.h"
37
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39
40 #ifdef HAVE_SYS_STAT_H
41 #include <sys/stat.h>
42 #endif
43 #include <regex.h>          /* for regcomp(3) */
44 #include <sys/file.h>       /* for flock(2) */
45 #include <signal.h>         /* for pthread_sigmask(3) */
46 #include <stdlib.h>         /* for closefrom(3) */
47 #include <sys/types.h>
48 #include <sys/wait.h>       /* for waitpid(2) */
49 #ifndef HAVE_CLOSEFROM
50 #include <dirent.h>         /* for opendir(3)   */
51 #endif
52 #ifdef HAVE_CAP
53 #include <sys/capability.h>
54 #endif /* HAVE_CAP */
55
56 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
57 #include "asterisk/channel.h"
58 #include "asterisk/pbx.h"
59 #include "asterisk/file.h"
60 #include "asterisk/app.h"
61 #include "asterisk/dsp.h"
62 #include "asterisk/utils.h"
63 #include "asterisk/lock.h"
64 #include "asterisk/indications.h"
65 #include "asterisk/linkedlists.h"
66 #include "asterisk/threadstorage.h"
67 #include "asterisk/test.h"
68 #include "asterisk/module.h"
69
70 AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
71
72 static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
73
74 struct zombie {
75         pid_t pid;
76         AST_LIST_ENTRY(zombie) list;
77 };
78
79 static AST_LIST_HEAD_STATIC(zombies, zombie);
80
81 static void *shaun_of_the_dead(void *data)
82 {
83         struct zombie *cur;
84         int status;
85         for (;;) {
86                 if (!AST_LIST_EMPTY(&zombies)) {
87                         /* Don't allow cancellation while we have a lock. */
88                         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
89                         AST_LIST_LOCK(&zombies);
90                         AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
91                                 if (waitpid(cur->pid, &status, WNOHANG) != 0) {
92                                         AST_LIST_REMOVE_CURRENT(list);
93                                         ast_free(cur);
94                                 }
95                         }
96                         AST_LIST_TRAVERSE_SAFE_END
97                         AST_LIST_UNLOCK(&zombies);
98                         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
99                 }
100                 pthread_testcancel();
101                 /* Wait for 60 seconds, without engaging in a busy loop. */
102                 ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
103         }
104         return NULL;
105 }
106
107
108 #define AST_MAX_FORMATS 10
109
110 static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
111
112 /*!
113  * \brief This function presents a dialtone and reads an extension into 'collect'
114  * which must be a pointer to a **pre-initialized** array of char having a
115  * size of 'size' suitable for writing to.  It will collect no more than the smaller
116  * of 'maxlen' or 'size' minus the original strlen() of collect digits.
117  * \param chan struct.
118  * \param context
119  * \param collect
120  * \param size
121  * \param maxlen
122  * \param timeout timeout in milliseconds
123  *
124  * \return 0 if extension does not exist, 1 if extension exists
125 */
126 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
127 {
128         struct ast_tone_zone_sound *ts;
129         int res = 0, x = 0;
130
131         if (maxlen > size) {
132                 maxlen = size;
133         }
134
135         if (!timeout) {
136                 if (ast_channel_pbx(chan) && ast_channel_pbx(chan)->dtimeoutms) {
137                         timeout = ast_channel_pbx(chan)->dtimeoutms;
138                 } else {
139                         timeout = 5000;
140                 }
141         }
142
143         if ((ts = ast_get_indication_tone(ast_channel_zone(chan), "dial"))) {
144                 res = ast_playtones_start(chan, 0, ts->data, 0);
145                 ts = ast_tone_zone_sound_unref(ts);
146         } else {
147                 ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
148         }
149
150         for (x = strlen(collect); x < maxlen; ) {
151                 res = ast_waitfordigit(chan, timeout);
152                 if (!ast_ignore_pattern(context, collect)) {
153                         ast_playtones_stop(chan);
154                 }
155                 if (res < 1) {
156                         break;
157                 }
158                 if (res == '#') {
159                         break;
160                 }
161                 collect[x++] = res;
162                 if (!ast_matchmore_extension(chan, context, collect, 1,
163                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
164                         break;
165                 }
166         }
167
168         if (res >= 0) {
169                 res = ast_exists_extension(chan, context, collect, 1,
170                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL)) ? 1 : 0;
171         }
172
173         return res;
174 }
175
176 /*!
177  * \brief ast_app_getdata
178  * \param c The channel to read from
179  * \param prompt The file to stream to the channel
180  * \param s The string to read in to.  Must be at least the size of your length
181  * \param maxlen How many digits to read (maximum)
182  * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for
183  *      "ludicrous time" (essentially never times out) */
184 enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
185 {
186         int res = 0, to, fto;
187         char *front, *filename;
188
189         /* XXX Merge with full version? XXX */
190
191         if (maxlen)
192                 s[0] = '\0';
193
194         if (!prompt)
195                 prompt = "";
196
197         filename = ast_strdupa(prompt);
198         while ((front = strsep(&filename, "&"))) {
199                 ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", front, ast_channel_name(c));
200                 if (!ast_strlen_zero(front)) {
201                         res = ast_streamfile(c, front, ast_channel_language(c));
202                         if (res)
203                                 continue;
204                 }
205                 if (ast_strlen_zero(filename)) {
206                         /* set timeouts for the last prompt */
207                         fto = ast_channel_pbx(c) ? ast_channel_pbx(c)->rtimeoutms : 6000;
208                         to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
209
210                         if (timeout > 0) {
211                                 fto = to = timeout;
212                         }
213                         if (timeout < 0) {
214                                 fto = to = 1000000000;
215                         }
216                 } else {
217                         /* there is more than one prompt, so
218                          * get rid of the long timeout between
219                          * prompts, and make it 50ms */
220                         fto = 50;
221                         to = ast_channel_pbx(c) ? ast_channel_pbx(c)->dtimeoutms : 2000;
222                 }
223                 res = ast_readstring(c, s, maxlen, to, fto, "#");
224                 if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
225                         return res;
226                 }
227                 if (!ast_strlen_zero(s)) {
228                         return res;
229                 }
230         }
231
232         return res;
233 }
234
235 /* The lock type used by ast_lock_path() / ast_unlock_path() */
236 static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
237
238 int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
239 {
240         int res, to = 2000, fto = 6000;
241
242         if (!ast_strlen_zero(prompt)) {
243                 res = ast_streamfile(c, prompt, ast_channel_language(c));
244                 if (res < 0) {
245                         return res;
246                 }
247         }
248
249         if (timeout > 0) {
250                 fto = to = timeout;
251         }
252         if (timeout < 0) {
253                 fto = to = 1000000000;
254         }
255
256         res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
257
258         return res;
259 }
260
261 int ast_app_exec_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_args)
262 {
263         struct ast_app *macro_app;
264         int res;
265
266         macro_app = pbx_findapp("Macro");
267         if (!macro_app) {
268                 ast_log(LOG_WARNING,
269                         "Cannot run 'Macro(%s)'.  The application is not available.\n", macro_args);
270                 return -1;
271         }
272         if (autoservice_chan) {
273                 ast_autoservice_start(autoservice_chan);
274         }
275
276         ast_debug(4, "%s Original location: %s,%s,%d\n", ast_channel_name(macro_chan),
277                 ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
278                 ast_channel_priority(macro_chan));
279
280         res = pbx_exec(macro_chan, macro_app, macro_args);
281         ast_debug(4, "Macro exited with status %d\n", res);
282
283         /*
284          * Assume anything negative from Macro is an error.
285          * Anything else is success.
286          */
287         if (res < 0) {
288                 res = -1;
289         } else {
290                 res = 0;
291         }
292
293         ast_debug(4, "%s Ending location: %s,%s,%d\n", ast_channel_name(macro_chan),
294                 ast_channel_context(macro_chan), ast_channel_exten(macro_chan),
295                 ast_channel_priority(macro_chan));
296
297         if (autoservice_chan) {
298                 ast_autoservice_stop(autoservice_chan);
299         }
300         return res;
301 }
302
303 int ast_app_run_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char *macro_name, const char *macro_args)
304 {
305         int res;
306         char *args_str;
307         size_t args_len;
308
309         if (ast_strlen_zero(macro_args)) {
310                 return ast_app_exec_macro(autoservice_chan, macro_chan, macro_name);
311         }
312
313         /* Create the Macro application argument string. */
314         args_len = strlen(macro_name) + strlen(macro_args) + 2;
315         args_str = ast_malloc(args_len);
316         if (!args_str) {
317                 return -1;
318         }
319         snprintf(args_str, args_len, "%s,%s", macro_name, macro_args);
320
321         res = ast_app_exec_macro(autoservice_chan, macro_chan, args_str);
322         ast_free(args_str);
323         return res;
324 }
325
326 static const struct ast_app_stack_funcs *app_stack_callbacks;
327
328 void ast_install_stack_functions(const struct ast_app_stack_funcs *funcs)
329 {
330         app_stack_callbacks = funcs;
331 }
332
333 const char *ast_app_expand_sub_args(struct ast_channel *chan, const char *args)
334 {
335         const struct ast_app_stack_funcs *funcs;
336         const char *new_args;
337
338         funcs = app_stack_callbacks;
339         if (!funcs || !funcs->expand_sub_args) {
340                 ast_log(LOG_WARNING,
341                         "Cannot expand 'Gosub(%s)' arguments.  The app_stack module is not available.\n",
342                         args);
343                 return NULL;
344         }
345         ast_module_ref(funcs->module);
346
347         new_args = funcs->expand_sub_args(chan, args);
348         ast_module_unref(funcs->module);
349         return new_args;
350 }
351
352 int ast_app_exec_sub(struct ast_channel *autoservice_chan, struct ast_channel *sub_chan, const char *sub_args, int ignore_hangup)
353 {
354         const struct ast_app_stack_funcs *funcs;
355         int res;
356
357         funcs = app_stack_callbacks;
358         if (!funcs || !funcs->run_sub) {
359                 ast_log(LOG_WARNING,
360                         "Cannot run 'Gosub(%s)'.  The app_stack module is not available.\n",
361                         sub_args);
362                 return -1;
363         }
364         ast_module_ref(funcs->module);
365
366         if (autoservice_chan) {
367                 ast_autoservice_start(autoservice_chan);
368         }
369
370         res = funcs->run_sub(sub_chan, sub_args, ignore_hangup);
371         ast_module_unref(funcs->module);
372
373         if (autoservice_chan) {
374                 ast_autoservice_stop(autoservice_chan);
375         }
376         return res;
377 }
378
379 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)
380 {
381         int res;
382         char *args_str;
383         size_t args_len;
384
385         if (ast_strlen_zero(sub_args)) {
386                 return ast_app_exec_sub(autoservice_chan, sub_chan, sub_location, ignore_hangup);
387         }
388
389         /* Create the Gosub application argument string. */
390         args_len = strlen(sub_location) + strlen(sub_args) + 3;
391         args_str = ast_malloc(args_len);
392         if (!args_str) {
393                 return -1;
394         }
395         snprintf(args_str, args_len, "%s(%s)", sub_location, sub_args);
396
397         res = ast_app_exec_sub(autoservice_chan, sub_chan, args_str, ignore_hangup);
398         ast_free(args_str);
399         return res;
400 }
401
402 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
403 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
404 static int (*ast_inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs) = NULL;
405 static int (*ast_sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context) = NULL;
406 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
407 static int (*ast_copy_recording_to_vm_func)(struct ast_vm_recording_data *vm_rec_data) = NULL;
408 static const char *(*ast_vm_index_to_foldername_func)(int id) = NULL;
409 static struct ast_vm_mailbox_snapshot *(*ast_vm_mailbox_snapshot_create_func)(const char *mailbox,
410         const char *context,
411         const char *folder,
412         int descending,
413         enum ast_vm_snapshot_sort_val sort_val,
414         int combine_INBOX_and_OLD) = NULL;
415 static struct ast_vm_mailbox_snapshot *(*ast_vm_mailbox_snapshot_destroy_func)(struct ast_vm_mailbox_snapshot *mailbox_snapshot) = NULL;
416 static int (*ast_vm_msg_move_func)(const char *mailbox,
417         const char *context,
418         size_t num_msgs,
419         const char *oldfolder,
420         const char *old_msg_ids[],
421         const char *newfolder) = NULL;
422 static int (*ast_vm_msg_remove_func)(const char *mailbox,
423         const char *context,
424         size_t num_msgs,
425         const char *folder,
426         const char *msgs[]) = NULL;
427 static int (*ast_vm_msg_forward_func)(const char *from_mailbox,
428         const char *from_context,
429         const char *from_folder,
430         const char *to_mailbox,
431         const char *to_context,
432         const char *to_folder,
433         size_t num_msgs,
434         const char *msg_ids[],
435         int delete_old) = NULL;
436 static int (*ast_vm_msg_play_func)(struct ast_channel *chan,
437         const char *mailbox,
438         const char *context,
439         const char *folder,
440         const char *msg_num,
441         ast_vm_msg_play_cb cb) = NULL;
442
443 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
444                               int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
445                               int (*inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs),
446                               int (*messagecount_func)(const char *context, const char *mailbox, const char *folder),
447                               int (*sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context),
448                               int (*copy_recording_to_vm_func)(struct ast_vm_recording_data *vm_rec_data),
449                               const char *vm_index_to_foldername_func(int id),
450                               struct ast_vm_mailbox_snapshot *(*vm_mailbox_snapshot_create_func)(const char *mailbox,
451                                 const char *context,
452                                 const char *folder,
453                                 int descending,
454                                 enum ast_vm_snapshot_sort_val sort_val,
455                                 int combine_INBOX_and_OLD),
456                               struct ast_vm_mailbox_snapshot *(*vm_mailbox_snapshot_destroy_func)(struct ast_vm_mailbox_snapshot *mailbox_snapshot),
457                               int (*vm_msg_move_func)(const char *mailbox,
458                                 const char *context,
459                                 size_t num_msgs,
460                                 const char *oldfolder,
461                                 const char *old_msg_ids[],
462                                 const char *newfolder),
463                               int (*vm_msg_remove_func)(const char *mailbox,
464                                 const char *context,
465                                 size_t num_msgs,
466                                 const char *folder,
467                                 const char *msgs[]),
468                               int (*vm_msg_forward_func)(const char *from_mailbox,
469                                 const char *from_context,
470                                 const char *from_folder,
471                                 const char *to_mailbox,
472                                 const char *to_context,
473                                 const char *to_folder,
474                                 size_t num_msgs,
475                                 const char *msg_ids[],
476                                 int delete_old),
477                               int (*vm_msg_play_func)(struct ast_channel *chan,
478                                 const char *mailbox,
479                                 const char *context,
480                                 const char *folder,
481                                 const char *msg_num,
482                                 ast_vm_msg_play_cb cb))
483 {
484         ast_has_voicemail_func = has_voicemail_func;
485         ast_inboxcount_func = inboxcount_func;
486         ast_inboxcount2_func = inboxcount2_func;
487         ast_messagecount_func = messagecount_func;
488         ast_sayname_func = sayname_func;
489         ast_copy_recording_to_vm_func = copy_recording_to_vm_func;
490         ast_vm_index_to_foldername_func = vm_index_to_foldername_func;
491         ast_vm_mailbox_snapshot_create_func = vm_mailbox_snapshot_create_func;
492         ast_vm_mailbox_snapshot_destroy_func = vm_mailbox_snapshot_destroy_func;
493         ast_vm_msg_move_func = vm_msg_move_func;
494         ast_vm_msg_remove_func = vm_msg_remove_func;
495         ast_vm_msg_forward_func = vm_msg_forward_func;
496         ast_vm_msg_play_func = vm_msg_play_func;
497 }
498
499 void ast_uninstall_vm_functions(void)
500 {
501         ast_has_voicemail_func = NULL;
502         ast_inboxcount_func = NULL;
503         ast_inboxcount2_func = NULL;
504         ast_messagecount_func = NULL;
505         ast_sayname_func = NULL;
506         ast_copy_recording_to_vm_func = NULL;
507         ast_vm_index_to_foldername_func = NULL;
508         ast_vm_mailbox_snapshot_create_func = NULL;
509         ast_vm_mailbox_snapshot_destroy_func = NULL;
510         ast_vm_msg_move_func = NULL;
511         ast_vm_msg_remove_func = NULL;
512         ast_vm_msg_forward_func = NULL;
513         ast_vm_msg_play_func = NULL;
514 }
515
516 #ifdef TEST_FRAMEWORK
517 int (*ast_vm_test_create_user_func)(const char *context, const char *mailbox) = NULL;
518 int (*ast_vm_test_destroy_user_func)(const char *context, const char *mailbox) = NULL;
519
520 void ast_install_vm_test_functions(int (*vm_test_create_user_func)(const char *context, const char *mailbox),
521                                    int (*vm_test_destroy_user_func)(const char *context, const char *mailbox))
522 {
523         ast_vm_test_create_user_func = vm_test_create_user_func;
524         ast_vm_test_destroy_user_func = vm_test_destroy_user_func;
525 }
526
527 void ast_uninstall_vm_test_functions(void)
528 {
529         ast_vm_test_create_user_func = NULL;
530         ast_vm_test_destroy_user_func = NULL;
531 }
532 #endif
533
534 int ast_app_has_voicemail(const char *mailbox, const char *folder)
535 {
536         static int warned = 0;
537         if (ast_has_voicemail_func) {
538                 return ast_has_voicemail_func(mailbox, folder);
539         }
540
541         if (warned++ % 10 == 0) {
542                 ast_verb(3, "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
543         }
544         return 0;
545 }
546
547 /*!
548  * \internal
549  * \brief Function used as a callback for ast_copy_recording_to_vm when a real one isn't installed.
550  * \param vm_rec_data Stores crucial information about the voicemail that will basically just be used
551  * to figure out what the name of the recipient was supposed to be
552  */
553 int ast_app_copy_recording_to_vm(struct ast_vm_recording_data *vm_rec_data)
554 {
555         static int warned = 0;
556
557         if (ast_copy_recording_to_vm_func) {
558                 return ast_copy_recording_to_vm_func(vm_rec_data);
559         }
560
561         if (warned++ % 10 == 0) {
562                 ast_verb(3, "copy recording to voicemail called to copy %s.%s to %s@%s, but voicemail not loaded.\n",
563                         vm_rec_data->recording_file, vm_rec_data->recording_ext,
564                         vm_rec_data->mailbox, vm_rec_data->context);
565         }
566
567         return -1;
568 }
569
570 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
571 {
572         static int warned = 0;
573         if (newmsgs) {
574                 *newmsgs = 0;
575         }
576         if (oldmsgs) {
577                 *oldmsgs = 0;
578         }
579         if (ast_inboxcount_func) {
580                 return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
581         }
582
583         if (warned++ % 10 == 0) {
584                 ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
585         }
586
587         return 0;
588 }
589
590 int ast_app_inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
591 {
592         static int warned = 0;
593         if (newmsgs) {
594                 *newmsgs = 0;
595         }
596         if (oldmsgs) {
597                 *oldmsgs = 0;
598         }
599         if (urgentmsgs) {
600                 *urgentmsgs = 0;
601         }
602         if (ast_inboxcount2_func) {
603                 return ast_inboxcount2_func(mailbox, urgentmsgs, newmsgs, oldmsgs);
604         }
605
606         if (warned++ % 10 == 0) {
607                 ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
608         }
609
610         return 0;
611 }
612
613 int ast_app_sayname(struct ast_channel *chan, const char *mailbox, const char *context)
614 {
615         if (ast_sayname_func) {
616                 return ast_sayname_func(chan, mailbox, context);
617         }
618         return -1;
619 }
620
621 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
622 {
623         static int warned = 0;
624         if (ast_messagecount_func) {
625                 return ast_messagecount_func(context, mailbox, folder);
626         }
627
628         if (!warned) {
629                 warned++;
630                 ast_verb(3, "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
631         }
632
633         return 0;
634 }
635
636 const char *ast_vm_index_to_foldername(int id)
637 {
638         if (ast_vm_index_to_foldername_func) {
639                 return ast_vm_index_to_foldername_func(id);
640         }
641         return NULL;
642 }
643
644 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_create(const char *mailbox,
645         const char *context,
646         const char *folder,
647         int descending,
648         enum ast_vm_snapshot_sort_val sort_val,
649         int combine_INBOX_and_OLD)
650 {
651         if (ast_vm_mailbox_snapshot_create_func) {
652                 return ast_vm_mailbox_snapshot_create_func(mailbox, context, folder, descending, sort_val, combine_INBOX_and_OLD);
653         }
654         return NULL;
655 }
656
657 struct ast_vm_mailbox_snapshot *ast_vm_mailbox_snapshot_destroy(struct ast_vm_mailbox_snapshot *mailbox_snapshot)
658 {
659         if (ast_vm_mailbox_snapshot_destroy_func) {
660                 return ast_vm_mailbox_snapshot_destroy_func(mailbox_snapshot);
661         }
662         return NULL;
663 }
664
665 int ast_vm_msg_move(const char *mailbox,
666         const char *context,
667         size_t num_msgs,
668         const char *oldfolder,
669         const char *old_msg_ids[],
670         const char *newfolder)
671 {
672         if (ast_vm_msg_move_func) {
673                 return ast_vm_msg_move_func(mailbox, context, num_msgs, oldfolder, old_msg_ids, newfolder);
674         }
675         return 0;
676 }
677
678 int ast_vm_msg_remove(const char *mailbox,
679         const char *context,
680         size_t num_msgs,
681         const char *folder,
682         const char *msgs[])
683 {
684         if (ast_vm_msg_remove_func) {
685                 return ast_vm_msg_remove_func(mailbox, context, num_msgs, folder, msgs);
686         }
687         return 0;
688 }
689
690 int ast_vm_msg_forward(const char *from_mailbox,
691         const char *from_context,
692         const char *from_folder,
693         const char *to_mailbox,
694         const char *to_context,
695         const char *to_folder,
696         size_t num_msgs,
697         const char *msg_ids[],
698         int delete_old)
699 {
700         if (ast_vm_msg_forward_func) {
701                 return ast_vm_msg_forward_func(from_mailbox, from_context, from_folder, to_mailbox, to_context, to_folder, num_msgs, msg_ids, delete_old);
702         }
703         return 0;
704 }
705
706 int ast_vm_msg_play(struct ast_channel *chan,
707         const char *mailbox,
708         const char *context,
709         const char *folder,
710         const char *msg_num,
711         ast_vm_msg_play_cb cb)
712 {
713         if (ast_vm_msg_play_func) {
714                 return ast_vm_msg_play_func(chan, mailbox, context, folder, msg_num, cb);
715         }
716         return 0;
717 }
718
719 #ifdef TEST_FRAMEWORK
720 int ast_vm_test_create_user(const char *context, const char *mailbox)
721 {
722         if (ast_vm_test_create_user_func) {
723                 return ast_vm_test_create_user_func(context, mailbox);
724         }
725         return 0;
726 }
727
728 int ast_vm_test_destroy_user(const char *context, const char *mailbox)
729 {
730         if (ast_vm_test_destroy_user_func) {
731                 return ast_vm_test_destroy_user_func(context, mailbox);
732         }
733         return 0;
734 }
735 #endif
736
737 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
738 {
739         const char *ptr;
740         int res;
741         struct ast_silence_generator *silgen = NULL;
742
743         if (!between) {
744                 between = 100;
745         }
746
747         if (peer && ast_autoservice_start(peer)) {
748                 return -1;
749         }
750
751         /* Need a quiet time before sending digits. */
752         if (ast_opt_transmit_silence) {
753                 silgen = ast_channel_start_silence_generator(chan);
754         }
755         res = ast_safe_sleep(chan, 100);
756         if (res) {
757                 goto dtmf_stream_cleanup;
758         }
759
760         for (ptr = digits; *ptr; ptr++) {
761                 if (*ptr == 'w') {
762                         /* 'w' -- wait half a second */
763                         if ((res = ast_safe_sleep(chan, 500))) {
764                                 break;
765                         }
766                 } else if (*ptr == 'W') {
767                         /* 'W' -- wait a second */
768                         if ((res = ast_safe_sleep(chan, 1000))) {
769                                 break;
770                         }
771                 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
772                         if (*ptr == 'f' || *ptr == 'F') {
773                                 /* ignore return values if not supported by channel */
774                                 ast_indicate(chan, AST_CONTROL_FLASH);
775                         } else {
776                                 /* Character represents valid DTMF */
777                                 ast_senddigit(chan, *ptr, duration);
778                         }
779                         /* pause between digits */
780                         if ((res = ast_safe_sleep(chan, between))) {
781                                 break;
782                         }
783                 } else {
784                         ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
785                 }
786         }
787
788 dtmf_stream_cleanup:
789         if (silgen) {
790                 ast_channel_stop_silence_generator(chan, silgen);
791         }
792         if (peer && ast_autoservice_stop(peer)) {
793                 res = -1;
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                 regfree(&regexbuf_group);
1566                 return 0;
1567         }
1568
1569         AST_RWLIST_RDLOCK(&groups);
1570         AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1571                 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)))) {
1572                         count++;
1573                 }
1574         }
1575         AST_RWLIST_UNLOCK(&groups);
1576
1577         regfree(&regexbuf_group);
1578         if (!ast_strlen_zero(category)) {
1579                 regfree(&regexbuf_category);
1580         }
1581
1582         return count;
1583 }
1584
1585 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
1586 {
1587         struct ast_group_info *gi = NULL;
1588
1589         AST_RWLIST_WRLOCK(&groups);
1590         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1591                 if (gi->chan == old) {
1592                         gi->chan = new;
1593                 } else if (gi->chan == new) {
1594                         AST_RWLIST_REMOVE_CURRENT(group_list);
1595                         ast_free(gi);
1596                 }
1597         }
1598         AST_RWLIST_TRAVERSE_SAFE_END;
1599         AST_RWLIST_UNLOCK(&groups);
1600
1601         return 0;
1602 }
1603
1604 int ast_app_group_discard(struct ast_channel *chan)
1605 {
1606         struct ast_group_info *gi = NULL;
1607
1608         AST_RWLIST_WRLOCK(&groups);
1609         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1610                 if (gi->chan == chan) {
1611                         AST_RWLIST_REMOVE_CURRENT(group_list);
1612                         ast_free(gi);
1613                 }
1614         }
1615         AST_RWLIST_TRAVERSE_SAFE_END;
1616         AST_RWLIST_UNLOCK(&groups);
1617
1618         return 0;
1619 }
1620
1621 int ast_app_group_list_wrlock(void)
1622 {
1623         return AST_RWLIST_WRLOCK(&groups);
1624 }
1625
1626 int ast_app_group_list_rdlock(void)
1627 {
1628         return AST_RWLIST_RDLOCK(&groups);
1629 }
1630
1631 struct ast_group_info *ast_app_group_list_head(void)
1632 {
1633         return AST_RWLIST_FIRST(&groups);
1634 }
1635
1636 int ast_app_group_list_unlock(void)
1637 {
1638         return AST_RWLIST_UNLOCK(&groups);
1639 }
1640
1641 #undef ast_app_separate_args
1642 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
1643
1644 unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
1645 {
1646         int argc;
1647         char *scan, *wasdelim = NULL;
1648         int paren = 0, quote = 0, bracket = 0;
1649
1650         if (!array || !arraylen) {
1651                 return 0;
1652         }
1653
1654         memset(array, 0, arraylen * sizeof(*array));
1655
1656         if (!buf) {
1657                 return 0;
1658         }
1659
1660         scan = buf;
1661
1662         for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
1663                 array[argc] = scan;
1664                 for (; *scan; scan++) {
1665                         if (*scan == '(') {
1666                                 paren++;
1667                         } else if (*scan == ')') {
1668                                 if (paren) {
1669                                         paren--;
1670                                 }
1671                         } else if (*scan == '[') {
1672                                 bracket++;
1673                         } else if (*scan == ']') {
1674                                 if (bracket) {
1675                                         bracket--;
1676                                 }
1677                         } else if (*scan == '"' && delim != '"') {
1678                                 quote = quote ? 0 : 1;
1679                                 if (remove_chars) {
1680                                         /* Remove quote character from argument */
1681                                         memmove(scan, scan + 1, strlen(scan));
1682                                         scan--;
1683                                 }
1684                         } else if (*scan == '\\') {
1685                                 if (remove_chars) {
1686                                         /* Literal character, don't parse */
1687                                         memmove(scan, scan + 1, strlen(scan));
1688                                 } else {
1689                                         scan++;
1690                                 }
1691                         } else if ((*scan == delim) && !paren && !quote && !bracket) {
1692                                 wasdelim = scan;
1693                                 *scan++ = '\0';
1694                                 break;
1695                         }
1696                 }
1697         }
1698
1699         /* If the last character in the original string was the delimiter, then
1700          * there is one additional argument. */
1701         if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
1702                 array[argc++] = scan;
1703         }
1704
1705         return argc;
1706 }
1707
1708 /* ABI compatible function */
1709 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
1710 {
1711         return __ast_app_separate_args(buf, delim, 1, array, arraylen);
1712 }
1713
1714 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
1715 {
1716         char *s;
1717         char *fs;
1718         int res;
1719         int fd;
1720         int lp = strlen(path);
1721         time_t start;
1722
1723         s = ast_alloca(lp + 10);
1724         fs = ast_alloca(lp + 20);
1725
1726         snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
1727         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
1728         if (fd < 0) {
1729                 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
1730                 return AST_LOCK_PATH_NOT_FOUND;
1731         }
1732         close(fd);
1733
1734         snprintf(s, strlen(path) + 9, "%s/.lock", path);
1735         start = time(NULL);
1736         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
1737                 sched_yield();
1738         }
1739
1740         unlink(fs);
1741
1742         if (res) {
1743                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1744                 return AST_LOCK_TIMEOUT;
1745         } else {
1746                 ast_debug(1, "Locked path '%s'\n", path);
1747                 return AST_LOCK_SUCCESS;
1748         }
1749 }
1750
1751 static int ast_unlock_path_lockfile(const char *path)
1752 {
1753         char *s;
1754         int res;
1755
1756         s = ast_alloca(strlen(path) + 10);
1757
1758         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1759
1760         if ((res = unlink(s))) {
1761                 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
1762         } else {
1763                 ast_debug(1, "Unlocked path '%s'\n", path);
1764         }
1765
1766         return res;
1767 }
1768
1769 struct path_lock {
1770         AST_LIST_ENTRY(path_lock) le;
1771         int fd;
1772         char *path;
1773 };
1774
1775 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
1776
1777 static void path_lock_destroy(struct path_lock *obj)
1778 {
1779         if (obj->fd >= 0) {
1780                 close(obj->fd);
1781         }
1782         if (obj->path) {
1783                 free(obj->path);
1784         }
1785         free(obj);
1786 }
1787
1788 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
1789 {
1790         char *fs;
1791         int res;
1792         int fd;
1793         time_t start;
1794         struct path_lock *pl;
1795         struct stat st, ost;
1796
1797         fs = ast_alloca(strlen(path) + 20);
1798
1799         snprintf(fs, strlen(path) + 19, "%s/lock", path);
1800         if (lstat(fs, &st) == 0) {
1801                 if ((st.st_mode & S_IFMT) == S_IFLNK) {
1802                         ast_log(LOG_WARNING, "Unable to create lock file "
1803                                         "'%s': it's already a symbolic link\n",
1804                                         fs);
1805                         return AST_LOCK_FAILURE;
1806                 }
1807                 if (st.st_nlink > 1) {
1808                         ast_log(LOG_WARNING, "Unable to create lock file "
1809                                         "'%s': %u hard links exist\n",
1810                                         fs, (unsigned int) st.st_nlink);
1811                         return AST_LOCK_FAILURE;
1812                 }
1813         }
1814         if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
1815                 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
1816                                 fs, strerror(errno));
1817                 return AST_LOCK_PATH_NOT_FOUND;
1818         }
1819         if (!(pl = ast_calloc(1, sizeof(*pl)))) {
1820                 /* We don't unlink the lock file here, on the possibility that
1821                  * someone else created it - better to leave a little mess
1822                  * than create a big one by destroying someone else's lock
1823                  * and causing something to be corrupted.
1824                  */
1825                 close(fd);
1826                 return AST_LOCK_FAILURE;
1827         }
1828         pl->fd = fd;
1829         pl->path = strdup(path);
1830
1831         time(&start);
1832         while (
1833                 #ifdef SOLARIS
1834                 ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
1835                 #else
1836                 ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
1837                 #endif
1838                         (errno == EWOULDBLOCK) &&
1839                         (time(NULL) - start < 5))
1840                 usleep(1000);
1841         if (res) {
1842                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
1843                                 path, strerror(errno));
1844                 /* No unlinking of lock done, since we tried and failed to
1845                  * flock() it.
1846                  */
1847                 path_lock_destroy(pl);
1848                 return AST_LOCK_TIMEOUT;
1849         }
1850
1851         /* Check for the race where the file is recreated or deleted out from
1852          * underneath us.
1853          */
1854         if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
1855                         st.st_dev != ost.st_dev &&
1856                         st.st_ino != ost.st_ino) {
1857                 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
1858                                 "file changed underneath us\n", fs);
1859                 path_lock_destroy(pl);
1860                 return AST_LOCK_FAILURE;
1861         }
1862
1863         /* Success: file created, flocked, and is the one we started with */
1864         AST_LIST_LOCK(&path_lock_list);
1865         AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
1866         AST_LIST_UNLOCK(&path_lock_list);
1867
1868         ast_debug(1, "Locked path '%s'\n", path);
1869
1870         return AST_LOCK_SUCCESS;
1871 }
1872
1873 static int ast_unlock_path_flock(const char *path)
1874 {
1875         char *s;
1876         struct path_lock *p;
1877
1878         s = ast_alloca(strlen(path) + 20);
1879
1880         AST_LIST_LOCK(&path_lock_list);
1881         AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
1882                 if (!strcmp(p->path, path)) {
1883                         AST_LIST_REMOVE_CURRENT(le);
1884                         break;
1885                 }
1886         }
1887         AST_LIST_TRAVERSE_SAFE_END;
1888         AST_LIST_UNLOCK(&path_lock_list);
1889
1890         if (p) {
1891                 snprintf(s, strlen(path) + 19, "%s/lock", path);
1892                 unlink(s);
1893                 path_lock_destroy(p);
1894                 ast_debug(1, "Unlocked path '%s'\n", path);
1895         } else {
1896                 ast_debug(1, "Failed to unlock path '%s': "
1897                                 "lock not found\n", path);
1898         }
1899
1900         return 0;
1901 }
1902
1903 void ast_set_lock_type(enum AST_LOCK_TYPE type)
1904 {
1905         ast_lock_type = type;
1906 }
1907
1908 enum AST_LOCK_RESULT ast_lock_path(const char *path)
1909 {
1910         enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
1911
1912         switch (ast_lock_type) {
1913         case AST_LOCK_TYPE_LOCKFILE:
1914                 r = ast_lock_path_lockfile(path);
1915                 break;
1916         case AST_LOCK_TYPE_FLOCK:
1917                 r = ast_lock_path_flock(path);
1918                 break;
1919         }
1920
1921         return r;
1922 }
1923
1924 int ast_unlock_path(const char *path)
1925 {
1926         int r = 0;
1927
1928         switch (ast_lock_type) {
1929         case AST_LOCK_TYPE_LOCKFILE:
1930                 r = ast_unlock_path_lockfile(path);
1931                 break;
1932         case AST_LOCK_TYPE_FLOCK:
1933                 r = ast_unlock_path_flock(path);
1934                 break;
1935         }
1936
1937         return r;
1938 }
1939
1940 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path)
1941 {
1942         int silencethreshold;
1943         int maxsilence = 0;
1944         int res = 0;
1945         int cmd = 0;
1946         int max_attempts = 3;
1947         int attempts = 0;
1948         int recorded = 0;
1949         int message_exists = 0;
1950         /* Note that urgent and private are for flagging messages as such in the future */
1951
1952         /* barf if no pointer passed to store duration in */
1953         if (!duration) {
1954                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1955                 return -1;
1956         }
1957
1958         cmd = '3';       /* Want to start by recording */
1959
1960         silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
1961
1962         while ((cmd >= 0) && (cmd != 't')) {
1963                 switch (cmd) {
1964                 case '1':
1965                         if (!message_exists) {
1966                                 /* In this case, 1 is to record a message */
1967                                 cmd = '3';
1968                                 break;
1969                         } else {
1970                                 ast_stream_and_wait(chan, "vm-msgsaved", "");
1971                                 cmd = 't';
1972                                 return res;
1973                         }
1974                 case '2':
1975                         /* Review */
1976                         ast_verb(3, "Reviewing the recording\n");
1977                         cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
1978                         break;
1979                 case '3':
1980                         message_exists = 0;
1981                         /* Record */
1982                         ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
1983                         recorded = 1;
1984                         if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
1985                                 /* User has hung up, no options to give */
1986                                 return cmd;
1987                         }
1988                         if (cmd == '0') {
1989                                 break;
1990                         } else if (cmd == '*') {
1991                                 break;
1992                         } else {
1993                                 /* If all is well, a message exists */
1994                                 message_exists = 1;
1995                                 cmd = 0;
1996                         }
1997                         break;
1998                 case '4':
1999                 case '5':
2000                 case '6':
2001                 case '7':
2002                 case '8':
2003                 case '9':
2004                 case '*':
2005                 case '#':
2006                         cmd = ast_play_and_wait(chan, "vm-sorry");
2007                         break;
2008                 default:
2009                         if (message_exists) {
2010                                 cmd = ast_play_and_wait(chan, "vm-review");
2011                         } else {
2012                                 if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
2013                                         cmd = ast_waitfordigit(chan, 600);
2014                                 }
2015                         }
2016
2017                         if (!cmd) {
2018                                 cmd = ast_waitfordigit(chan, 6000);
2019                         }
2020                         if (!cmd) {
2021                                 attempts++;
2022                         }
2023                         if (attempts > max_attempts) {
2024                                 cmd = 't';
2025                         }
2026                 }
2027         }
2028         if (cmd == 't') {
2029                 cmd = 0;
2030         }
2031         return cmd;
2032 }
2033
2034 #define RES_UPONE (1 << 16)
2035 #define RES_EXIT  (1 << 17)
2036 #define RES_REPEAT (1 << 18)
2037 #define RES_RESTART ((1 << 19) | RES_REPEAT)
2038
2039 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
2040
2041 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
2042 {
2043         int res;
2044         int (*ivr_func)(struct ast_channel *, void *);
2045         char *c;
2046         char *n;
2047
2048         switch (option->action) {
2049         case AST_ACTION_UPONE:
2050                 return RES_UPONE;
2051         case AST_ACTION_EXIT:
2052                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
2053         case AST_ACTION_REPEAT:
2054                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
2055         case AST_ACTION_RESTART:
2056                 return RES_RESTART ;
2057         case AST_ACTION_NOOP:
2058                 return 0;
2059         case AST_ACTION_BACKGROUND:
2060                 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
2061                 if (res < 0) {
2062                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2063                         res = 0;
2064                 }
2065                 return res;
2066         case AST_ACTION_PLAYBACK:
2067                 res = ast_stream_and_wait(chan, (char *)option->adata, "");
2068                 if (res < 0) {
2069                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
2070                         res = 0;
2071                 }
2072                 return res;
2073         case AST_ACTION_MENU:
2074                 if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
2075                         /* Do not pass entry errors back up, treat as though it was an "UPONE" */
2076                         res = 0;
2077                 }
2078                 return res;
2079         case AST_ACTION_WAITOPTION:
2080                 if (!(res = ast_waitfordigit(chan, ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000))) {
2081                         return 't';
2082                 }
2083                 return res;
2084         case AST_ACTION_CALLBACK:
2085                 ivr_func = option->adata;
2086                 res = ivr_func(chan, cbdata);
2087                 return res;
2088         case AST_ACTION_TRANSFER:
2089                 res = ast_parseable_goto(chan, option->adata);
2090                 return 0;
2091         case AST_ACTION_PLAYLIST:
2092         case AST_ACTION_BACKLIST:
2093                 res = 0;
2094                 c = ast_strdupa(option->adata);
2095                 while ((n = strsep(&c, ";"))) {
2096                         if ((res = ast_stream_and_wait(chan, n,
2097                                         (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
2098                                 break;
2099                         }
2100                 }
2101                 ast_stopstream(chan);
2102                 return res;
2103         default:
2104                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
2105                 return 0;
2106         }
2107         return -1;
2108 }
2109
2110 static int option_exists(struct ast_ivr_menu *menu, char *option)
2111 {
2112         int x;
2113         for (x = 0; menu->options[x].option; x++) {
2114                 if (!strcasecmp(menu->options[x].option, option)) {
2115                         return x;
2116                 }
2117         }
2118         return -1;
2119 }
2120
2121 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
2122 {
2123         int x;
2124         for (x = 0; menu->options[x].option; x++) {
2125                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
2126                                 (menu->options[x].option[strlen(option)])) {
2127                         return x;
2128                 }
2129         }
2130         return -1;
2131 }
2132
2133 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
2134 {
2135         int res = 0;
2136         int ms;
2137         while (option_matchmore(menu, exten)) {
2138                 ms = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
2139                 if (strlen(exten) >= maxexten - 1) {
2140                         break;
2141                 }
2142                 if ((res = ast_waitfordigit(chan, ms)) < 1) {
2143                         break;
2144                 }
2145                 exten[strlen(exten) + 1] = '\0';
2146                 exten[strlen(exten)] = res;
2147         }
2148         return res > 0 ? 0 : res;
2149 }
2150
2151 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2152 {
2153         /* Execute an IVR menu structure */
2154         int res = 0;
2155         int pos = 0;
2156         int retries = 0;
2157         char exten[AST_MAX_EXTENSION] = "s";
2158         if (option_exists(menu, "s") < 0) {
2159                 strcpy(exten, "g");
2160                 if (option_exists(menu, "g") < 0) {
2161                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
2162                         return -1;
2163                 }
2164         }
2165         while (!res) {
2166                 while (menu->options[pos].option) {
2167                         if (!strcasecmp(menu->options[pos].option, exten)) {
2168                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
2169                                 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
2170                                 if (res < 0) {
2171                                         break;
2172                                 } else if (res & RES_UPONE) {
2173                                         return 0;
2174                                 } else if (res & RES_EXIT) {
2175                                         return res;
2176                                 } else if (res & RES_REPEAT) {
2177                                         int maxretries = res & 0xffff;
2178                                         if ((res & RES_RESTART) == RES_RESTART) {
2179                                                 retries = 0;
2180                                         } else {
2181                                                 retries++;
2182                                         }
2183                                         if (!maxretries) {
2184                                                 maxretries = 3;
2185                                         }
2186                                         if ((maxretries > 0) && (retries >= maxretries)) {
2187                                                 ast_debug(1, "Max retries %d exceeded\n", maxretries);
2188                                                 return -2;
2189                                         } else {
2190                                                 if (option_exists(menu, "g") > -1) {
2191                                                         strcpy(exten, "g");
2192                                                 } else if (option_exists(menu, "s") > -1) {
2193                                                         strcpy(exten, "s");
2194                                                 }
2195                                         }
2196                                         pos = 0;
2197                                         continue;
2198                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
2199                                         ast_debug(1, "Got start of extension, %c\n", res);
2200                                         exten[1] = '\0';
2201                                         exten[0] = res;
2202                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
2203                                                 break;
2204                                         }
2205                                         if (option_exists(menu, exten) < 0) {
2206                                                 if (option_exists(menu, "i")) {
2207                                                         ast_debug(1, "Invalid extension entered, going to 'i'!\n");
2208                                                         strcpy(exten, "i");
2209                                                         pos = 0;
2210                                                         continue;
2211                                                 } else {
2212                                                         ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
2213                                                         res = -2;
2214                                                         break;
2215                                                 }
2216                                         } else {
2217                                                 ast_debug(1, "New existing extension: %s\n", exten);
2218                                                 pos = 0;
2219                                                 continue;
2220                                         }
2221                                 }
2222                         }
2223                         pos++;
2224                 }
2225                 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
2226                 pos = 0;
2227                 if (!strcasecmp(exten, "s")) {
2228                         strcpy(exten, "g");
2229                 } else {
2230                         break;
2231                 }
2232         }
2233         return res;
2234 }
2235
2236 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
2237 {
2238         int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
2239         /* Hide internal coding */
2240         return res > 0 ? 0 : res;
2241 }
2242
2243 char *ast_read_textfile(const char *filename)
2244 {
2245         int fd, count = 0, res;
2246         char *output = NULL;
2247         struct stat filesize;
2248
2249         if (stat(filename, &filesize) == -1) {
2250                 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
2251                 return NULL;
2252         }
2253
2254         count = filesize.st_size + 1;
2255
2256         if ((fd = open(filename, O_RDONLY)) < 0) {
2257                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
2258                 return NULL;
2259         }
2260
2261         if ((output = ast_malloc(count))) {
2262                 res = read(fd, output, count - 1);
2263                 if (res == count - 1) {
2264                         output[res] = '\0';
2265                 } else {
2266                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
2267                         ast_free(output);
2268                         output = NULL;
2269                 }
2270         }
2271
2272         close(fd);
2273
2274         return output;
2275 }
2276
2277 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
2278 {
2279         char *s, *arg;
2280         int curarg, res = 0;
2281         unsigned int argloc;
2282         struct ast_flags *flags = _flags;
2283         struct ast_flags64 *flags64 = _flags;
2284
2285         if (flaglen == 32) {
2286                 ast_clear_flag(flags, AST_FLAGS_ALL);
2287         } else {
2288                 flags64->flags = 0;
2289         }
2290
2291         if (!optstr) {
2292                 return 0;
2293         }
2294
2295         s = optstr;
2296         while (*s) {
2297                 curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
2298                 argloc = options[curarg].arg_index;
2299                 if (*s == '(') {
2300                         int paren = 1, quote = 0;
2301                         int parsequotes = (s[1] == '"') ? 1 : 0;
2302
2303                         /* Has argument */
2304                         arg = ++s;
2305                         for (; *s; s++) {
2306                                 if (*s == '(' && !quote) {
2307                                         paren++;
2308                                 } else if (*s == ')' && !quote) {
2309                                         /* Count parentheses, unless they're within quotes (or backslashed, below) */
2310                                         paren--;
2311                                 } else if (*s == '"' && parsequotes) {
2312                                         /* Leave embedded quotes alone, unless they are the first character */
2313                                         quote = quote ? 0 : 1;
2314                                         ast_copy_string(s, s + 1, INT_MAX);
2315                                         s--;
2316                                 } else if (*s == '\\') {
2317                                         if (!quote) {
2318                                                 /* If a backslash is found outside of quotes, remove it */
2319                                                 ast_copy_string(s, s + 1, INT_MAX);
2320                                         } else if (quote && s[1] == '"') {
2321                                                 /* Backslash for a quote character within quotes, remove the backslash */
2322                                                 ast_copy_string(s, s + 1, INT_MAX);
2323                                         } else {
2324                                                 /* Backslash within quotes, keep both characters */
2325                                                 s++;
2326                                         }
2327                                 }
2328
2329                                 if (paren == 0) {
2330                                         break;
2331                                 }
2332                         }
2333                         /* This will find the closing paren we found above, or none, if the string ended before we found one. */
2334                         if ((s = strchr(s, ')'))) {
2335                                 if (argloc) {
2336                                         args[argloc - 1] = arg;
2337                                 }
2338                                 *s++ = '\0';
2339                         } else {
2340                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
2341                                 res = -1;
2342                                 break;
2343                         }
2344                 } else if (argloc) {
2345                         args[argloc - 1] = "";
2346                 }
2347                 if (flaglen == 32) {
2348                         ast_set_flag(flags, options[curarg].flag);
2349                 } else {
2350                         ast_set_flag64(flags64, options[curarg].flag);
2351                 }
2352         }
2353
2354         return res;
2355 }
2356
2357 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
2358 {
2359         return parse_options(options, flags, args, optstr, 32);
2360 }
2361
2362 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
2363 {
2364         return parse_options(options, flags, args, optstr, 64);
2365 }
2366
2367 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
2368 {
2369         unsigned int i, found = 0;
2370         for (i = 32; i < 128 && found < len; i++) {
2371                 if (ast_test_flag64(flags, options[i].flag)) {
2372                         buf[found++] = i;
2373                 }
2374         }
2375         buf[found] = '\0';
2376 }
2377
2378 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
2379 {
2380         int i;
2381         *consumed = 1;
2382         *result = 0;
2383         if (ast_strlen_zero(stream)) {
2384                 *consumed = 0;
2385                 return -1;
2386         }
2387
2388         if (*stream == '\\') {
2389                 *consumed = 2;
2390                 switch (*(stream + 1)) {
2391                 case 'n':
2392                         *result = '\n';
2393                         break;
2394                 case 'r':
2395                         *result = '\r';
2396                         break;
2397                 case 't':
2398                         *result = '\t';
2399                         break;
2400                 case 'x':
2401                         /* Hexadecimal */
2402                         if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
2403                                 *consumed = 3;
2404                                 if (*(stream + 2) <= '9') {
2405                                         *result = *(stream + 2) - '0';
2406                                 } else if (*(stream + 2) <= 'F') {
2407                                         *result = *(stream + 2) - 'A' + 10;
2408                                 } else {
2409                                         *result = *(stream + 2) - 'a' + 10;
2410                                 }
2411                         } else {
2412                                 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
2413                                 return -1;
2414                         }
2415
2416                         if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
2417                                 *consumed = 4;
2418                                 *result <<= 4;
2419                                 if (*(stream + 3) <= '9') {
2420                                         *result += *(stream + 3) - '0';
2421                                 } else if (*(stream + 3) <= 'F') {
2422                                         *result += *(stream + 3) - 'A' + 10;
2423                                 } else {
2424                                         *result += *(stream + 3) - 'a' + 10;
2425                                 }
2426                         }
2427                         break;
2428                 case '0':
2429                         /* Octal */
2430                         *consumed = 2;
2431                         for (i = 2; ; i++) {
2432                                 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
2433                                         (*consumed)++;
2434                                         ast_debug(5, "result was %d, ", *result);
2435                                         *result <<= 3;
2436                                         *result += *(stream + i) - '0';
2437                                         ast_debug(5, "is now %d\n", *result);
2438                                 } else {
2439                                         break;
2440                                 }
2441                         }
2442                         break;
2443                 default:
2444                         *result = *(stream + 1);
2445                 }
2446         } else {
2447                 *result = *stream;
2448                 *consumed = 1;
2449         }
2450         return 0;
2451 }
2452
2453 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
2454 {
2455         char *cur = result;
2456         size_t consumed;
2457
2458         while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
2459                 cur++;
2460                 stream += consumed;
2461         }
2462         *cur = '\0';
2463         return result;
2464 }
2465
2466 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
2467 {
2468         char next, *buf;
2469         size_t offset = 0;
2470         size_t consumed;
2471
2472         if (strchr(stream, '\\')) {
2473                 while (!ast_get_encoded_char(stream, &next, &consumed)) {
2474                         if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
2475                                 ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
2476                         }
2477                         if (offset + 2 > ast_str_size(*str)) {
2478                                 break;
2479                         }
2480                         buf = ast_str_buffer(*str);
2481                         buf[offset++] = next;
2482                         stream += consumed;
2483                 }
2484                 buf = ast_str_buffer(*str);
2485                 buf[offset++] = '\0';
2486                 ast_str_update(*str);
2487         } else {
2488                 ast_str_set(str, maxlen, "%s", stream);
2489         }
2490         return 0;
2491 }
2492
2493 void ast_close_fds_above_n(int n)
2494 {
2495         closefrom(n + 1);
2496 }
2497
2498 int ast_safe_fork(int stop_reaper)
2499 {
2500         sigset_t signal_set, old_set;
2501         int pid;
2502
2503         /* Don't let the default signal handler for children reap our status */
2504         if (stop_reaper) {
2505                 ast_replace_sigchld();
2506         }
2507
2508         sigfillset(&signal_set);
2509         pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
2510
2511         pid = fork();
2512
2513         if (pid != 0) {
2514                 /* Fork failed or parent */
2515                 pthread_sigmask(SIG_SETMASK, &old_set, NULL);
2516                 if (!stop_reaper && pid > 0) {
2517                         struct zombie *cur = ast_calloc(1, sizeof(*cur));
2518                         if (cur) {
2519                                 cur->pid = pid;
2520                                 AST_LIST_LOCK(&zombies);
2521                                 AST_LIST_INSERT_TAIL(&zombies, cur, list);
2522                                 AST_LIST_UNLOCK(&zombies);
2523                                 if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
2524                                         if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
2525                                                 ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
2526                                                 shaun_of_the_dead_thread = AST_PTHREADT_NULL;
2527                                         }
2528                                 }
2529                         }
2530                 }
2531                 return pid;
2532         } else {
2533                 /* Child */
2534 #ifdef HAVE_CAP
2535                 cap_t cap = cap_from_text("cap_net_admin-eip");
2536
2537                 if (cap_set_proc(cap)) {
2538                         ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
2539                 }
2540                 cap_free(cap);
2541 #endif
2542
2543                 /* Before we unblock our signals, return our trapped signals back to the defaults */
2544                 signal(SIGHUP, SIG_DFL);
2545                 signal(SIGCHLD, SIG_DFL);
2546                 signal(SIGINT, SIG_DFL);
2547                 signal(SIGURG, SIG_DFL);
2548                 signal(SIGTERM, SIG_DFL);
2549                 signal(SIGPIPE, SIG_DFL);
2550                 signal(SIGXFSZ, SIG_DFL);
2551
2552                 /* unblock important signal handlers */
2553                 if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
2554                         ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
2555                         _exit(1);
2556                 }
2557
2558                 return pid;
2559         }
2560 }
2561
2562 void ast_safe_fork_cleanup(void)
2563 {
2564         ast_unreplace_sigchld();
2565 }
2566
2567 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
2568 {
2569         int res;
2570         char u[10];
2571 #ifdef HAVE_LONG_DOUBLE_WIDER
2572         long double amount;
2573         #define FMT "%30Lf%9s"
2574 #else
2575         double amount;
2576         #define FMT "%30lf%9s"
2577 #endif
2578         if (!timestr) {
2579                 return -1;
2580         }
2581
2582         if ((res = sscanf(timestr, FMT, &amount, u)) == 0) {
2583 #undef FMT
2584                 return -1;
2585         } else if (res == 2) {
2586                 switch (u[0]) {
2587                 case 'h':
2588                 case 'H':
2589                         unit = TIMELEN_HOURS;
2590                         break;
2591                 case 's':
2592                 case 'S':
2593                         unit = TIMELEN_SECONDS;
2594                         break;
2595                 case 'm':
2596                 case 'M':
2597                         if (toupper(u[1]) == 'S') {
2598                                 unit = TIMELEN_MILLISECONDS;
2599                         } else if (u[1] == '\0') {
2600                                 unit = TIMELEN_MINUTES;
2601                         }
2602                         break;
2603                 }
2604         }
2605
2606         switch (unit) {
2607         case TIMELEN_HOURS:
2608                 amount *= 60;
2609                 /* fall-through */
2610         case TIMELEN_MINUTES:
2611                 amount *= 60;
2612                 /* fall-through */
2613         case TIMELEN_SECONDS:
2614                 amount *= 1000;
2615                 /* fall-through */
2616         case TIMELEN_MILLISECONDS:
2617                 ;
2618         }
2619         *result = amount > INT_MAX ? INT_MAX : (int) amount;
2620         return 0;
2621 }
2622