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