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