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