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