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