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