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