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