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