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