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