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