Add Asterisk TestSuite event hooks to support ConfBridge testing
[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 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #ifdef HAVE_SYS_STAT_H
31 #include <sys/stat.h>
32 #endif
33 #include <regex.h>          /* for regcomp(3) */
34 #include <sys/file.h>       /* for flock(2) */
35 #include <signal.h>         /* for pthread_sigmask(3) */
36 #include <stdlib.h>         /* for closefrom(3) */
37 #include <sys/types.h>
38 #include <sys/wait.h>       /* for waitpid(2) */
39 #ifndef HAVE_CLOSEFROM
40 #include <dirent.h>         /* for opendir(3)   */
41 #endif
42 #ifdef HAVE_CAP
43 #include <sys/capability.h>
44 #endif /* HAVE_CAP */
45
46 #include "asterisk/paths.h"     /* use ast_config_AST_DATA_DIR */
47 #include "asterisk/channel.h"
48 #include "asterisk/pbx.h"
49 #include "asterisk/file.h"
50 #include "asterisk/app.h"
51 #include "asterisk/dsp.h"
52 #include "asterisk/utils.h"
53 #include "asterisk/lock.h"
54 #include "asterisk/indications.h"
55 #include "asterisk/linkedlists.h"
56 #include "asterisk/threadstorage.h"
57 #include "asterisk/test.h"
58
59 AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
60
61 static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
62
63 struct zombie {
64         pid_t pid;
65         AST_LIST_ENTRY(zombie) list;
66 };
67
68 static AST_LIST_HEAD_STATIC(zombies, zombie);
69
70 static void *shaun_of_the_dead(void *data)
71 {
72         struct zombie *cur;
73         int status;
74         for (;;) {
75                 if (!AST_LIST_EMPTY(&zombies)) {
76                         /* Don't allow cancellation while we have a lock. */
77                         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
78                         AST_LIST_LOCK(&zombies);
79                         AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
80                                 if (waitpid(cur->pid, &status, WNOHANG) != 0) {
81                                         AST_LIST_REMOVE_CURRENT(list);
82                                         ast_free(cur);
83                                 }
84                         }
85                         AST_LIST_TRAVERSE_SAFE_END
86                         AST_LIST_UNLOCK(&zombies);
87                         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
88                 }
89                 pthread_testcancel();
90                 /* Wait for 60 seconds, without engaging in a busy loop. */
91                 ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
92         }
93         return NULL;
94 }
95
96
97 #define AST_MAX_FORMATS 10
98
99 static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
100
101 /*!
102  * \brief This function presents a dialtone and reads an extension into 'collect'
103  * which must be a pointer to a **pre-initialized** array of char having a
104  * size of 'size' suitable for writing to.  It will collect no more than the smaller
105  * of 'maxlen' or 'size' minus the original strlen() of collect digits.
106  * \param chan struct.
107  * \param context
108  * \param collect
109  * \param size
110  * \param maxlen
111  * \param timeout timeout in seconds
112  *
113  * \return 0 if extension does not exist, 1 if extension exists
114 */
115 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
116 {
117         struct ast_tone_zone_sound *ts;
118         int res = 0, x = 0;
119
120         if (maxlen > size) {
121                 maxlen = size;
122         }
123
124         if (!timeout && chan->pbx) {
125                 timeout = chan->pbx->dtimeoutms / 1000.0;
126         } else if (!timeout) {
127                 timeout = 5;
128         }
129
130         if ((ts = ast_get_indication_tone(chan->zone, "dial"))) {
131                 res = ast_playtones_start(chan, 0, ts->data, 0);
132                 ts = ast_tone_zone_sound_unref(ts);
133         } else {
134                 ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
135         }
136
137         for (x = strlen(collect); x < maxlen; ) {
138                 res = ast_waitfordigit(chan, timeout);
139                 if (!ast_ignore_pattern(context, collect)) {
140                         ast_playtones_stop(chan);
141                 }
142                 if (res < 1) {
143                         break;
144                 }
145                 if (res == '#') {
146                         break;
147                 }
148                 collect[x++] = res;
149                 if (!ast_matchmore_extension(chan, context, collect, 1,
150                         S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
151                         break;
152                 }
153         }
154
155         if (res >= 0) {
156                 res = ast_exists_extension(chan, context, collect, 1,
157                         S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)) ? 1 : 0;
158         }
159
160         return res;
161 }
162
163 /*!
164  * \brief ast_app_getdata
165  * \param c The channel to read from
166  * \param prompt The file to stream to the channel
167  * \param s The string to read in to.  Must be at least the size of your length
168  * \param maxlen How many digits to read (maximum)
169  * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for 
170  *      "ludicrous time" (essentially never times out) */
171 enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
172 {
173         int res = 0, to, fto;
174         char *front, *filename;
175
176         /* XXX Merge with full version? XXX */
177
178         if (maxlen)
179                 s[0] = '\0';
180
181         if (!prompt)
182                 prompt = "";
183
184         filename = ast_strdupa(prompt);
185         while ((front = strsep(&filename, "&"))) {
186                 ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", front, c->name);
187                 if (!ast_strlen_zero(front)) {
188                         res = ast_streamfile(c, front, c->language);
189                         if (res)
190                                 continue;
191                 }
192                 if (ast_strlen_zero(filename)) {
193                         /* set timeouts for the last prompt */
194                         fto = c->pbx ? c->pbx->rtimeoutms : 6000;
195                         to = c->pbx ? c->pbx->dtimeoutms : 2000;
196
197                         if (timeout > 0) {
198                                 fto = to = timeout;
199                         }
200                         if (timeout < 0) {
201                                 fto = to = 1000000000;
202                         }
203                 } else {
204                         /* there is more than one prompt, so
205                          * get rid of the long timeout between
206                          * prompts, and make it 50ms */
207                         fto = 50;
208                         to = c->pbx ? c->pbx->dtimeoutms : 2000;
209                 }
210                 res = ast_readstring(c, s, maxlen, to, fto, "#");
211                 if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
212                         return res;
213                 }
214                 if (!ast_strlen_zero(s)) {
215                         return res;
216                 }
217         }
218
219         return res;
220 }
221
222 /* The lock type used by ast_lock_path() / ast_unlock_path() */
223 static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
224
225 int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
226 {
227         int res, to = 2000, fto = 6000;
228
229         if (!ast_strlen_zero(prompt)) {
230                 res = ast_streamfile(c, prompt, c->language);
231                 if (res < 0) {
232                         return res;
233                 }
234         }
235
236         if (timeout > 0) {
237                 fto = to = timeout;
238         }
239         if (timeout < 0) {
240                 fto = to = 1000000000;
241         }
242
243         res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
244
245         return res;
246 }
247
248 int ast_app_run_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char * const macro_name, const char * const macro_args)
249 {
250         struct ast_app *macro_app;
251         int res;
252         char buf[1024];
253
254         macro_app = pbx_findapp("Macro");
255         if (!macro_app) {
256                 ast_log(LOG_WARNING, "Cannot run macro '%s' because the 'Macro' application in not available\n", macro_name);
257                 return -1;
258         }
259         snprintf(buf, sizeof(buf), "%s%s%s", macro_name, ast_strlen_zero(macro_args) ? "" : ",", S_OR(macro_args, ""));
260         if (autoservice_chan) {
261                 ast_autoservice_start(autoservice_chan);
262         }
263         res = pbx_exec(macro_chan, macro_app, buf);
264         if (autoservice_chan) {
265                 ast_autoservice_stop(autoservice_chan);
266         }
267         return res;
268 }
269
270 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
271 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
272 static int (*ast_inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs) = NULL;
273 static int (*ast_sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context) = NULL;
274 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
275
276 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
277                               int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
278                               int (*inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs),
279                               int (*messagecount_func)(const char *context, const char *mailbox, const char *folder),
280                               int (*sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context))
281 {
282         ast_has_voicemail_func = has_voicemail_func;
283         ast_inboxcount_func = inboxcount_func;
284         ast_inboxcount2_func = inboxcount2_func;
285         ast_messagecount_func = messagecount_func;
286         ast_sayname_func = sayname_func;
287 }
288
289 void ast_uninstall_vm_functions(void)
290 {
291         ast_has_voicemail_func = NULL;
292         ast_inboxcount_func = NULL;
293         ast_inboxcount2_func = NULL;
294         ast_messagecount_func = NULL;
295         ast_sayname_func = NULL;
296 }
297
298 int ast_app_has_voicemail(const char *mailbox, const char *folder)
299 {
300         static int warned = 0;
301         if (ast_has_voicemail_func) {
302                 return ast_has_voicemail_func(mailbox, folder);
303         }
304
305         if (warned++ % 10 == 0) {
306                 ast_verb(3, "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
307         }
308         return 0;
309 }
310
311
312 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
313 {
314         static int warned = 0;
315         if (newmsgs) {
316                 *newmsgs = 0;
317         }
318         if (oldmsgs) {
319                 *oldmsgs = 0;
320         }
321         if (ast_inboxcount_func) {
322                 return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
323         }
324
325         if (warned++ % 10 == 0) {
326                 ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
327         }
328
329         return 0;
330 }
331
332 int ast_app_inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
333 {
334         static int warned = 0;
335         if (newmsgs) {
336                 *newmsgs = 0;
337         }
338         if (oldmsgs) {
339                 *oldmsgs = 0;
340         }
341         if (urgentmsgs) {
342                 *urgentmsgs = 0;
343         }
344         if (ast_inboxcount_func) {
345                 return ast_inboxcount2_func(mailbox, urgentmsgs, newmsgs, oldmsgs);
346         }
347
348         if (warned++ % 10 == 0) {
349                 ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
350         }
351
352         return 0;
353 }
354
355 int ast_app_sayname(struct ast_channel *chan, const char *mailbox, const char *context)
356 {
357         if (ast_sayname_func) {
358                 return ast_sayname_func(chan, mailbox, context);
359         }
360         return -1;
361 }
362
363 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
364 {
365         static int warned = 0;
366         if (ast_messagecount_func) {
367                 return ast_messagecount_func(context, mailbox, folder);
368         }
369
370         if (!warned) {
371                 warned++;
372                 ast_verb(3, "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
373         }
374
375         return 0;
376 }
377
378 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
379 {
380         const char *ptr;
381         int res = 0;
382         struct ast_silence_generator *silgen = NULL;
383
384         if (!between) {
385                 between = 100;
386         }
387
388         if (peer) {
389                 res = ast_autoservice_start(peer);
390         }
391
392         if (!res) {
393                 res = ast_waitfor(chan, 100);
394         }
395
396         /* ast_waitfor will return the number of remaining ms on success */
397         if (res < 0) {
398                 if (peer) {
399                         ast_autoservice_stop(peer);
400                 }
401                 return res;
402         }
403
404         if (ast_opt_transmit_silence) {
405                 silgen = ast_channel_start_silence_generator(chan);
406         }
407
408         for (ptr = digits; *ptr; ptr++) {
409                 if (*ptr == 'w') {
410                         /* 'w' -- wait half a second */
411                         if ((res = ast_safe_sleep(chan, 500))) {
412                                 break;
413                         }
414                 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
415                         /* Character represents valid DTMF */
416                         if (*ptr == 'f' || *ptr == 'F') {
417                                 /* ignore return values if not supported by channel */
418                                 ast_indicate(chan, AST_CONTROL_FLASH);
419                         } else {
420                                 ast_senddigit(chan, *ptr, duration);
421                         }
422                         /* pause between digits */
423                         if ((res = ast_safe_sleep(chan, between))) {
424                                 break;
425                         }
426                 } else {
427                         ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
428                 }
429         }
430
431         if (peer) {
432                 /* Stop autoservice on the peer channel, but don't overwrite any error condition
433                    that has occurred previously while acting on the primary channel */
434                 if (ast_autoservice_stop(peer) && !res) {
435                         res = -1;
436                 }
437         }
438
439         if (silgen) {
440                 ast_channel_stop_silence_generator(chan, silgen);
441         }
442
443         return res;
444 }
445
446 struct linear_state {
447         int fd;
448         int autoclose;
449         int allowoverride;
450         struct ast_format origwfmt;
451 };
452
453 static void linear_release(struct ast_channel *chan, void *params)
454 {
455         struct linear_state *ls = params;
456
457         if (ls->origwfmt.id && ast_set_write_format(chan, &ls->origwfmt)) {
458                 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt.id);
459         }
460
461         if (ls->autoclose) {
462                 close(ls->fd);
463         }
464
465         ast_free(params);
466 }
467
468 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
469 {
470         short buf[2048 + AST_FRIENDLY_OFFSET / 2];
471         struct linear_state *ls = data;
472         struct ast_frame f = {
473                 .frametype = AST_FRAME_VOICE,
474                 .data.ptr = buf + AST_FRIENDLY_OFFSET / 2,
475                 .offset = AST_FRIENDLY_OFFSET,
476         };
477         int res;
478
479         ast_format_set(&f.subclass.format, AST_FORMAT_SLINEAR, 0);
480
481         len = samples * 2;
482         if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
483                 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" , len);
484                 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
485         }
486         res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
487         if (res > 0) {
488                 f.datalen = res;
489                 f.samples = res / 2;
490                 ast_write(chan, &f);
491                 if (res == len) {
492                         return 0;
493                 }
494         }
495         return -1;
496 }
497
498 static void *linear_alloc(struct ast_channel *chan, void *params)
499 {
500         struct linear_state *ls = params;
501
502         if (!params) {
503                 return NULL;
504         }
505
506         /* In this case, params is already malloc'd */
507         if (ls->allowoverride) {
508                 ast_set_flag(chan, AST_FLAG_WRITE_INT);
509         } else {
510                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
511         }
512
513         ast_format_copy(&ls->origwfmt, &chan->writeformat);
514
515         if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR)) {
516                 ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
517                 ast_free(ls);
518                 ls = params = NULL;
519         }
520
521         return params;
522 }
523
524 static struct ast_generator linearstream =
525 {
526         alloc: linear_alloc,
527         release: linear_release,
528         generate: linear_generator,
529 };
530
531 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
532 {
533         struct linear_state *lin;
534         char tmpf[256];
535         int res = -1;
536         int autoclose = 0;
537         if (fd < 0) {
538                 if (ast_strlen_zero(filename)) {
539                         return -1;
540                 }
541                 autoclose = 1;
542                 if (filename[0] == '/') {
543                         ast_copy_string(tmpf, filename, sizeof(tmpf));
544                 } else {
545                         snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
546                 }
547                 if ((fd = open(tmpf, O_RDONLY)) < 0) {
548                         ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
549                         return -1;
550                 }
551         }
552         if ((lin = ast_calloc(1, sizeof(*lin)))) {
553                 lin->fd = fd;
554                 lin->allowoverride = allowoverride;
555                 lin->autoclose = autoclose;
556                 res = ast_activate_generator(chan, &linearstream, lin);
557         }
558         return res;
559 }
560
561 int ast_control_streamfile(struct ast_channel *chan, const char *file,
562                            const char *fwd, const char *rev,
563                            const char *stop, const char *suspend,
564                            const char *restart, int skipms, long *offsetms)
565 {
566         char *breaks = NULL;
567         char *end = NULL;
568         int blen = 2;
569         int res;
570         long pause_restart_point = 0;
571         long offset = 0;
572
573         if (offsetms) {
574                 offset = *offsetms * 8; /* XXX Assumes 8kHz */
575         }
576
577         if (stop) {
578                 blen += strlen(stop);
579         }
580         if (suspend) {
581                 blen += strlen(suspend);
582         }
583         if (restart) {
584                 blen += strlen(restart);
585         }
586
587         if (blen > 2) {
588                 breaks = alloca(blen + 1);
589                 breaks[0] = '\0';
590                 if (stop) {
591                         strcat(breaks, stop);
592                 }
593                 if (suspend) {
594                         strcat(breaks, suspend);
595                 }
596                 if (restart) {
597                         strcat(breaks, restart);
598                 }
599         }
600         if (chan->_state != AST_STATE_UP) {
601                 res = ast_answer(chan);
602         }
603
604         if (file) {
605                 if ((end = strchr(file, ':'))) {
606                         if (!strcasecmp(end, ":end")) {
607                                 *end = '\0';
608                                 end++;
609                         }
610                 }
611         }
612
613         for (;;) {
614                 ast_stopstream(chan);
615                 res = ast_streamfile(chan, file, chan->language);
616                 if (!res) {
617                         if (pause_restart_point) {
618                                 ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
619                                 pause_restart_point = 0;
620                         }
621                         else if (end || offset < 0) {
622                                 if (offset == -8) {
623                                         offset = 0;
624                                 }
625                                 ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
626
627                                 ast_seekstream(chan->stream, offset, SEEK_END);
628                                 end = NULL;
629                                 offset = 0;
630                         } else if (offset) {
631                                 ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
632                                 ast_seekstream(chan->stream, offset, SEEK_SET);
633                                 offset = 0;
634                         }
635                         res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
636                 }
637
638                 if (res < 1) {
639                         break;
640                 }
641
642                 /* We go at next loop if we got the restart char */
643                 if (restart && strchr(restart, res)) {
644                         ast_debug(1, "we'll restart the stream here at next loop\n");
645                         pause_restart_point = 0;
646                         continue;
647                 }
648
649                 if (suspend && strchr(suspend, res)) {
650                         pause_restart_point = ast_tellstream(chan->stream);
651                         for (;;) {
652                                 ast_stopstream(chan);
653                                 if (!(res = ast_waitfordigit(chan, 1000))) {
654                                         continue;
655                                 } else if (res == -1 || strchr(suspend, res) || (stop && strchr(stop, res))) {
656                                         break;
657                                 }
658                         }
659                         if (res == *suspend) {
660                                 res = 0;
661                                 continue;
662                         }
663                 }
664
665                 if (res == -1) {
666                         break;
667                 }
668
669                 /* if we get one of our stop chars, return it to the calling function */
670                 if (stop && strchr(stop, res)) {
671                         break;
672                 }
673         }
674
675         if (pause_restart_point) {
676                 offset = pause_restart_point;
677         } else {
678                 if (chan->stream) {
679                         offset = ast_tellstream(chan->stream);
680                 } else {
681                         offset = -8;  /* indicate end of file */
682                 }
683         }
684
685         if (offsetms) {
686                 *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
687         }
688
689         /* If we are returning a digit cast it as char */
690         if (res > 0 || chan->stream) {
691                 res = (char)res;
692         }
693
694         ast_stopstream(chan);
695
696         return res;
697 }
698
699 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
700 {
701         int d = 0;
702
703         ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", fn, chan->name);
704         if ((d = ast_streamfile(chan, fn, chan->language))) {
705                 return d;
706         }
707
708         d = ast_waitstream(chan, AST_DIGIT_ANY);
709
710         ast_stopstream(chan);
711
712         return d;
713 }
714
715 static int global_silence_threshold = 128;
716 static int global_maxsilence = 0;
717
718 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
719  * \param chan Channel to playback to/record from.
720  * \param playfile Filename of sound to play before recording begins.
721  * \param recordfile Filename to record to.
722  * \param maxtime Maximum length of recording (in seconds).
723  * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
724  * \param duration Where to store actual length of the recorded message (in milliseconds).
725  * \param sound_duration Where to store the length of the recorded message (in milliseconds), minus any silence
726  * \param beep Whether to play a beep before starting to record.
727  * \param silencethreshold
728  * \param maxsilence Length of silence that will end a recording (in milliseconds).
729  * \param path Optional filesystem path to unlock.
730  * \param prepend If true, prepend the recorded audio to an existing file and follow prepend mode recording rules
731  * \param acceptdtmf DTMF digits that will end the recording.
732  * \param canceldtmf DTMF digits that will cancel the recording.
733  * \param skip_confirmation_sound If true, don't play auth-thankyou at end. Nice for custom recording prompts in apps.
734  *
735  * \retval -1 failure or hangup
736  * \retval 'S' Recording ended from silence timeout
737  * \retval 't' Recording ended from the message exceeding the maximum duration, or via DTMF in prepend mode
738  * \retval dtmfchar Recording ended via the return value's DTMF character for either cancel or accept.
739  */
740 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)
741 {
742         int d = 0;
743         char *fmts;
744         char comment[256];
745         int x, fmtcnt = 1, res = -1, outmsg = 0;
746         struct ast_filestream *others[AST_MAX_FORMATS];
747         char *sfmt[AST_MAX_FORMATS];
748         char *stringp = NULL;
749         time_t start, end;
750         struct ast_dsp *sildet = NULL;   /* silence detector dsp */
751         int totalsilence = 0;
752         int dspsilence = 0;
753         int olddspsilence = 0;
754         struct ast_format rfmt;
755         struct ast_silence_generator *silgen = NULL;
756         char prependfile[PATH_MAX];
757
758         ast_format_clear(&rfmt);
759         if (silencethreshold < 0) {
760                 silencethreshold = global_silence_threshold;
761         }
762
763         if (maxsilence < 0) {
764                 maxsilence = global_maxsilence;
765         }
766
767         /* barf if no pointer passed to store duration in */
768         if (!duration) {
769                 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
770                 return -1;
771         }
772
773         ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
774         snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
775
776         if (playfile || beep) {
777                 if (!beep) {
778                         d = ast_play_and_wait(chan, playfile);
779                 }
780                 if (d > -1) {
781                         d = ast_stream_and_wait(chan, "beep", "");
782                 }
783                 if (d < 0) {
784                         return -1;
785                 }
786         }
787
788         if (prepend) {
789                 ast_copy_string(prependfile, recordfile, sizeof(prependfile));
790                 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
791         }
792
793         fmts = ast_strdupa(fmt);
794
795         stringp = fmts;
796         strsep(&stringp, "|");
797         ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
798         sfmt[0] = ast_strdupa(fmts);
799
800         while ((fmt = strsep(&stringp, "|"))) {
801                 if (fmtcnt > AST_MAX_FORMATS - 1) {
802                         ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
803                         break;
804                 }
805                 sfmt[fmtcnt++] = ast_strdupa(fmt);
806         }
807
808         end = start = time(NULL);  /* pre-initialize end to be same as start in case we never get into loop */
809         for (x = 0; x < fmtcnt; x++) {
810                 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, AST_FILE_MODE);
811                 ast_verb(3, "x=%d, open writing:  %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
812
813                 if (!others[x]) {
814                         break;
815                 }
816         }
817
818         if (path) {
819                 ast_unlock_path(path);
820         }
821
822         if (maxsilence > 0) {
823                 sildet = ast_dsp_new(); /* Create the silence detector */
824                 if (!sildet) {
825                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
826                         return -1;
827                 }
828                 ast_dsp_set_threshold(sildet, silencethreshold);
829                 ast_format_copy(&rfmt, &chan->readformat);
830                 res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
831                 if (res < 0) {
832                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
833                         ast_dsp_free(sildet);
834                         return -1;
835                 }
836         }
837
838         if (!prepend) {
839                 /* Request a video update */
840                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
841
842                 if (ast_opt_transmit_silence) {
843                         silgen = ast_channel_start_silence_generator(chan);
844                 }
845         }
846
847         if (x == fmtcnt) {
848                 /* Loop forever, writing the packets we read to the writer(s), until
849                    we read a digit or get a hangup */
850                 struct ast_frame *f;
851                 for (;;) {
852                         if (!(res = ast_waitfor(chan, 2000))) {
853                                 ast_debug(1, "One waitfor failed, trying another\n");
854                                 /* Try one more time in case of masq */
855                                 if (!(res = ast_waitfor(chan, 2000))) {
856                                         ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
857                                         res = -1;
858                                 }
859                         }
860
861                         if (res < 0) {
862                                 f = NULL;
863                                 break;
864                         }
865                         if (!(f = ast_read(chan))) {
866                                 break;
867                         }
868                         if (f->frametype == AST_FRAME_VOICE) {
869                                 /* write each format */
870                                 for (x = 0; x < fmtcnt; x++) {
871                                         if (prepend && !others[x]) {
872                                                 break;
873                                         }
874                                         res = ast_writestream(others[x], f);
875                                 }
876
877                                 /* Silence Detection */
878                                 if (maxsilence > 0) {
879                                         dspsilence = 0;
880                                         ast_dsp_silence(sildet, f, &dspsilence);
881                                         if (olddspsilence > dspsilence) {
882                                                 totalsilence += olddspsilence;
883                                         }
884                                         olddspsilence = dspsilence;
885
886                                         if (dspsilence > maxsilence) {
887                                                 /* Ended happily with silence */
888                                                 ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
889                                                 res = 'S';
890                                                 outmsg = 2;
891                                                 break;
892                                         }
893                                 }
894                                 /* Exit on any error */
895                                 if (res) {
896                                         ast_log(LOG_WARNING, "Error writing frame\n");
897                                         break;
898                                 }
899                         } else if (f->frametype == AST_FRAME_VIDEO) {
900                                 /* Write only once */
901                                 ast_writestream(others[0], f);
902                         } else if (f->frametype == AST_FRAME_DTMF) {
903                                 if (prepend) {
904                                 /* stop recording with any digit */
905                                         ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
906                                         res = 't';
907                                         outmsg = 2;
908                                         break;
909                                 }
910                                 if (strchr(acceptdtmf, f->subclass.integer)) {
911                                         ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
912                                         res = f->subclass.integer;
913                                         outmsg = 2;
914                                         break;
915                                 }
916                                 if (strchr(canceldtmf, f->subclass.integer)) {
917                                         ast_verb(3, "User cancelled message by pressing %c\n", f->subclass.integer);
918                                         res = f->subclass.integer;
919                                         outmsg = 0;
920                                         break;
921                                 }
922                         }
923                         if (maxtime) {
924                                 end = time(NULL);
925                                 if (maxtime < (end - start)) {
926                                         ast_verb(3, "Took too long, cutting it short...\n");
927                                         res = 't';
928                                         outmsg = 2;
929                                         break;
930                                 }
931                         }
932                         ast_frfree(f);
933                 }
934                 if (!f) {
935                         ast_verb(3, "User hung up\n");
936                         res = -1;
937                         outmsg = 1;
938                 } else {
939                         ast_frfree(f);
940                 }
941         } else {
942                 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
943         }
944
945         if (!prepend) {
946                 if (silgen) {
947                         ast_channel_stop_silence_generator(chan, silgen);
948                 }
949         }
950
951         /*!\note
952          * Instead of asking how much time passed (end - start), calculate the number
953          * of seconds of audio which actually went into the file.  This fixes a
954          * problem where audio is stopped up on the network and never gets to us.
955          *
956          * Note that we still want to use the number of seconds passed for the max
957          * message, otherwise we could get a situation where this stream is never
958          * closed (which would create a resource leak).
959          */
960         *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
961         if (sound_duration) {
962                 *sound_duration = *duration;
963         }
964
965         if (!prepend) {
966                 /* Reduce duration by a total silence amount */
967                 if (olddspsilence <= dspsilence) {
968                         totalsilence += dspsilence;
969                 }
970
971                 if (sound_duration) {
972                         if (totalsilence > 0) {
973                                 *sound_duration -= (totalsilence - 200) / 1000;
974                         }
975                         if (*sound_duration < 0) {
976                                 *sound_duration = 0;
977                         }
978                 }
979
980                 if (dspsilence > 0) {
981                         *duration -= (dspsilence - 200) / 1000;
982                 }
983
984                 if (*duration < 0) {
985                         *duration = 0;
986                 }
987
988                 for (x = 0; x < fmtcnt; x++) {
989                         if (!others[x]) {
990                                 break;
991                         }
992                         /*!\note
993                          * If we ended with silence, trim all but the first 200ms of silence
994                          * off the recording.  However, if we ended with '#', we don't want
995                          * to trim ANY part of the recording.
996                          */
997                         if (res > 0 && dspsilence) {
998                                 /* rewind only the trailing silence */
999                                 ast_stream_rewind(others[x], dspsilence - 200);
1000                         }
1001                         ast_truncstream(others[x]);
1002                         ast_closestream(others[x]);
1003                 }
1004         }
1005
1006         if (prepend && outmsg) {
1007                 struct ast_filestream *realfiles[AST_MAX_FORMATS];
1008                 struct ast_frame *fr;
1009
1010                 for (x = 0; x < fmtcnt; x++) {
1011                         snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
1012                         realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
1013                         if (!others[x] || !realfiles[x]) {
1014                                 break;
1015                         }
1016                         /*!\note Same logic as above. */
1017                         if (dspsilence) {
1018                                 ast_stream_rewind(others[x], dspsilence - 200);
1019                         }
1020                         ast_truncstream(others[x]);
1021                         /* add the original file too */
1022                         while ((fr = ast_readframe(realfiles[x]))) {
1023                                 ast_writestream(others[x], fr);
1024                                 ast_frfree(fr);
1025                         }
1026                         ast_closestream(others[x]);
1027                         ast_closestream(realfiles[x]);
1028                         ast_filerename(prependfile, recordfile, sfmt[x]);
1029                         ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
1030                         ast_filedelete(prependfile, sfmt[x]);
1031                 }
1032         }
1033         if (rfmt.id && ast_set_read_format(chan, &rfmt)) {
1034                 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(&rfmt), chan->name);
1035         }
1036         if ((outmsg == 2) && (!skip_confirmation_sound)) {
1037                 ast_stream_and_wait(chan, "auth-thankyou", "");
1038         }
1039         if (sildet) {
1040                 ast_dsp_free(sildet);
1041         }
1042         return res;
1043 }
1044
1045 static const char default_acceptdtmf[] = "#";
1046 static const char default_canceldtmf[] = "";
1047
1048 int ast_play_and_record_full(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int silencethreshold, int maxsilence, const char *path, const char *acceptdtmf, const char *canceldtmf)
1049 {
1050         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, S_OR(acceptdtmf, default_acceptdtmf), S_OR(canceldtmf, default_canceldtmf), 0);
1051 }
1052
1053 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)
1054 {
1055         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf, 0);
1056 }
1057
1058 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)
1059 {
1060         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf, 1);
1061 }
1062
1063 /* Channel group core functions */
1064
1065 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
1066 {
1067         int res = 0;
1068         char tmp[256];
1069         char *grp = NULL, *cat = NULL;
1070
1071         if (!ast_strlen_zero(data)) {
1072                 ast_copy_string(tmp, data, sizeof(tmp));
1073                 grp = tmp;
1074                 if ((cat = strchr(tmp, '@'))) {
1075                         *cat++ = '\0';
1076                 }
1077         }
1078
1079         if (!ast_strlen_zero(grp)) {
1080                 ast_copy_string(group, grp, group_max);
1081         } else {
1082                 *group = '\0';
1083         }
1084
1085         if (!ast_strlen_zero(cat)) {
1086                 ast_copy_string(category, cat, category_max);
1087         }
1088
1089         return res;
1090 }
1091
1092 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
1093 {
1094         int res = 0;
1095         char group[80] = "", category[80] = "";
1096         struct ast_group_info *gi = NULL;
1097         size_t len = 0;
1098
1099         if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
1100                 return -1;
1101         }
1102
1103         /* Calculate memory we will need if this is new */
1104         len = sizeof(*gi) + strlen(group) + 1;
1105         if (!ast_strlen_zero(category)) {
1106                 len += strlen(category) + 1;
1107         }
1108
1109         AST_RWLIST_WRLOCK(&groups);
1110         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1111                 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1112                         AST_RWLIST_REMOVE_CURRENT(group_list);
1113                         free(gi);
1114                         break;
1115                 }
1116         }
1117         AST_RWLIST_TRAVERSE_SAFE_END;
1118
1119         if (ast_strlen_zero(group)) {
1120                 /* Enable unsetting the group */
1121         } else if ((gi = calloc(1, len))) {
1122                 gi->chan = chan;
1123                 gi->group = (char *) gi + sizeof(*gi);
1124                 strcpy(gi->group, group);
1125                 if (!ast_strlen_zero(category)) {
1126                         gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
1127                         strcpy(gi->category, category);
1128                 }
1129                 AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
1130         } else {
1131                 res = -1;
1132         }
1133
1134         AST_RWLIST_UNLOCK(&groups);
1135
1136         return res;
1137 }
1138
1139 int ast_app_group_get_count(const char *group, const char *category)
1140 {
1141         struct ast_group_info *gi = NULL;
1142         int count = 0;
1143
1144         if (ast_strlen_zero(group)) {
1145                 return 0;
1146         }
1147
1148         AST_RWLIST_RDLOCK(&groups);
1149         AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1150                 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1151                         count++;
1152                 }
1153         }
1154         AST_RWLIST_UNLOCK(&groups);
1155
1156         return count;
1157 }
1158
1159 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
1160 {
1161         struct ast_group_info *gi = NULL;
1162         regex_t regexbuf_group;
1163         regex_t regexbuf_category;
1164         int count = 0;
1165
1166         if (ast_strlen_zero(groupmatch)) {
1167                 ast_log(LOG_NOTICE, "groupmatch empty\n");
1168                 return 0;
1169         }
1170
1171         /* if regex compilation fails, return zero matches */
1172         if (regcomp(&regexbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
1173                 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
1174                 return 0;
1175         }
1176
1177         if (!ast_strlen_zero(category) && regcomp(&regexbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
1178                 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
1179                 return 0;
1180         }
1181
1182         AST_RWLIST_RDLOCK(&groups);
1183         AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1184                 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)))) {
1185                         count++;
1186                 }
1187         }
1188         AST_RWLIST_UNLOCK(&groups);
1189
1190         regfree(&regexbuf_group);
1191         if (!ast_strlen_zero(category)) {
1192                 regfree(&regexbuf_category);
1193         }
1194
1195         return count;
1196 }
1197
1198 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
1199 {
1200         struct ast_group_info *gi = NULL;
1201
1202         AST_RWLIST_WRLOCK(&groups);
1203         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1204                 if (gi->chan == old) {
1205                         gi->chan = new;
1206                 } else if (gi->chan == new) {
1207                         AST_RWLIST_REMOVE_CURRENT(group_list);
1208                         ast_free(gi);
1209                 }
1210         }
1211         AST_RWLIST_TRAVERSE_SAFE_END;
1212         AST_RWLIST_UNLOCK(&groups);
1213
1214         return 0;
1215 }
1216
1217 int ast_app_group_discard(struct ast_channel *chan)
1218 {
1219         struct ast_group_info *gi = NULL;
1220
1221         AST_RWLIST_WRLOCK(&groups);
1222         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1223                 if (gi->chan == chan) {
1224                         AST_RWLIST_REMOVE_CURRENT(group_list);
1225                         ast_free(gi);
1226                 }
1227         }
1228         AST_RWLIST_TRAVERSE_SAFE_END;
1229         AST_RWLIST_UNLOCK(&groups);
1230
1231         return 0;
1232 }
1233
1234 int ast_app_group_list_wrlock(void)
1235 {
1236         return AST_RWLIST_WRLOCK(&groups);
1237 }
1238
1239 int ast_app_group_list_rdlock(void)
1240 {
1241         return AST_RWLIST_RDLOCK(&groups);
1242 }
1243
1244 struct ast_group_info *ast_app_group_list_head(void)
1245 {
1246         return AST_RWLIST_FIRST(&groups);
1247 }
1248
1249 int ast_app_group_list_unlock(void)
1250 {
1251         return AST_RWLIST_UNLOCK(&groups);
1252 }
1253
1254 #undef ast_app_separate_args
1255 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
1256
1257 unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
1258 {
1259         int argc;
1260         char *scan, *wasdelim = NULL;
1261         int paren = 0, quote = 0, bracket = 0;
1262
1263         if (!array || !arraylen) {
1264                 return 0;
1265         }
1266
1267         memset(array, 0, arraylen * sizeof(*array));
1268
1269         if (!buf) {
1270                 return 0;
1271         }
1272
1273         scan = buf;
1274
1275         for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
1276                 array[argc] = scan;
1277                 for (; *scan; scan++) {
1278                         if (*scan == '(') {
1279                                 paren++;
1280                         } else if (*scan == ')') {
1281                                 if (paren) {
1282                                         paren--;
1283                                 }
1284                         } else if (*scan == '[') {
1285                                 bracket++;
1286                         } else if (*scan == ']') {
1287                                 if (bracket) {
1288                                         bracket--;
1289                                 }
1290                         } else if (*scan == '"' && delim != '"') {
1291                                 quote = quote ? 0 : 1;
1292                                 if (remove_chars) {
1293                                         /* Remove quote character from argument */
1294                                         memmove(scan, scan + 1, strlen(scan));
1295                                         scan--;
1296                                 }
1297                         } else if (*scan == '\\') {
1298                                 if (remove_chars) {
1299                                         /* Literal character, don't parse */
1300                                         memmove(scan, scan + 1, strlen(scan));
1301                                 } else {
1302                                         scan++;
1303                                 }
1304                         } else if ((*scan == delim) && !paren && !quote && !bracket) {
1305                                 wasdelim = scan;
1306                                 *scan++ = '\0';
1307                                 break;
1308                         }
1309                 }
1310         }
1311
1312         /* If the last character in the original string was the delimiter, then
1313          * there is one additional argument. */
1314         if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
1315                 array[argc++] = scan;
1316         }
1317
1318         return argc;
1319 }
1320
1321 /* ABI compatible function */
1322 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
1323 {
1324         return __ast_app_separate_args(buf, delim, 1, array, arraylen);
1325 }
1326
1327 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
1328 {
1329         char *s;
1330         char *fs;
1331         int res;
1332         int fd;
1333         int lp = strlen(path);
1334         time_t start;
1335
1336         s = alloca(lp + 10);
1337         fs = alloca(lp + 20);
1338
1339         snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
1340         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
1341         if (fd < 0) {
1342                 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
1343                 return AST_LOCK_PATH_NOT_FOUND;
1344         }
1345         close(fd);
1346
1347         snprintf(s, strlen(path) + 9, "%s/.lock", path);
1348         start = time(NULL);
1349         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
1350                 sched_yield();
1351         }
1352
1353         unlink(fs);
1354
1355         if (res) {
1356                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1357                 return AST_LOCK_TIMEOUT;
1358         } else {
1359                 ast_debug(1, "Locked path '%s'\n", path);
1360                 return AST_LOCK_SUCCESS;
1361         }
1362 }
1363
1364 static int ast_unlock_path_lockfile(const char *path)
1365 {
1366         char *s;
1367         int res;
1368
1369         s = alloca(strlen(path) + 10);
1370
1371         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1372
1373         if ((res = unlink(s))) {
1374                 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
1375         } else {
1376                 ast_debug(1, "Unlocked path '%s'\n", path);
1377         }
1378
1379         return res;
1380 }
1381
1382 struct path_lock {
1383         AST_LIST_ENTRY(path_lock) le;
1384         int fd;
1385         char *path;
1386 };
1387
1388 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
1389
1390 static void path_lock_destroy(struct path_lock *obj)
1391 {
1392         if (obj->fd >= 0) {
1393                 close(obj->fd);
1394         }
1395         if (obj->path) {
1396                 free(obj->path);
1397         }
1398         free(obj);
1399 }
1400
1401 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
1402 {
1403         char *fs;
1404         int res;
1405         int fd;
1406         time_t start;
1407         struct path_lock *pl;
1408         struct stat st, ost;
1409
1410         fs = alloca(strlen(path) + 20);
1411
1412         snprintf(fs, strlen(path) + 19, "%s/lock", path);
1413         if (lstat(fs, &st) == 0) {
1414                 if ((st.st_mode & S_IFMT) == S_IFLNK) {
1415                         ast_log(LOG_WARNING, "Unable to create lock file "
1416                                         "'%s': it's already a symbolic link\n",
1417                                         fs);
1418                         return AST_LOCK_FAILURE;
1419                 }
1420                 if (st.st_nlink > 1) {
1421                         ast_log(LOG_WARNING, "Unable to create lock file "
1422                                         "'%s': %u hard links exist\n",
1423                                         fs, (unsigned int) st.st_nlink);
1424                         return AST_LOCK_FAILURE;
1425                 }
1426         }
1427         if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
1428                 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
1429                                 fs, strerror(errno));
1430                 return AST_LOCK_PATH_NOT_FOUND;
1431         }
1432         if (!(pl = ast_calloc(1, sizeof(*pl)))) {
1433                 /* We don't unlink the lock file here, on the possibility that
1434                  * someone else created it - better to leave a little mess
1435                  * than create a big one by destroying someone else's lock
1436                  * and causing something to be corrupted.
1437                  */
1438                 close(fd);
1439                 return AST_LOCK_FAILURE;
1440         }
1441         pl->fd = fd;
1442         pl->path = strdup(path);
1443
1444         time(&start);
1445         while (
1446                 #ifdef SOLARIS
1447                 ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
1448                 #else
1449                 ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
1450                 #endif
1451                         (errno == EWOULDBLOCK) &&
1452                         (time(NULL) - start < 5))
1453                 usleep(1000);
1454         if (res) {
1455                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
1456                                 path, strerror(errno));
1457                 /* No unlinking of lock done, since we tried and failed to
1458                  * flock() it.
1459                  */
1460                 path_lock_destroy(pl);
1461                 return AST_LOCK_TIMEOUT;
1462         }
1463
1464         /* Check for the race where the file is recreated or deleted out from
1465          * underneath us.
1466          */
1467         if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
1468                         st.st_dev != ost.st_dev &&
1469                         st.st_ino != ost.st_ino) {
1470                 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
1471                                 "file changed underneath us\n", fs);
1472                 path_lock_destroy(pl);
1473                 return AST_LOCK_FAILURE;
1474         }
1475
1476         /* Success: file created, flocked, and is the one we started with */
1477         AST_LIST_LOCK(&path_lock_list);
1478         AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
1479         AST_LIST_UNLOCK(&path_lock_list);
1480
1481         ast_debug(1, "Locked path '%s'\n", path);
1482
1483         return AST_LOCK_SUCCESS;
1484 }
1485
1486 static int ast_unlock_path_flock(const char *path)
1487 {
1488         char *s;
1489         struct path_lock *p;
1490
1491         s = alloca(strlen(path) + 20);
1492
1493         AST_LIST_LOCK(&path_lock_list);
1494         AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
1495                 if (!strcmp(p->path, path)) {
1496                         AST_LIST_REMOVE_CURRENT(le);
1497                         break;
1498                 }
1499         }
1500         AST_LIST_TRAVERSE_SAFE_END;
1501         AST_LIST_UNLOCK(&path_lock_list);
1502
1503         if (p) {
1504                 snprintf(s, strlen(path) + 19, "%s/lock", path);
1505                 unlink(s);
1506                 path_lock_destroy(p);
1507                 ast_debug(1, "Unlocked path '%s'\n", path);
1508         } else {
1509                 ast_debug(1, "Failed to unlock path '%s': "
1510                                 "lock not found\n", path);
1511         }
1512
1513         return 0;
1514 }
1515
1516 void ast_set_lock_type(enum AST_LOCK_TYPE type)
1517 {
1518         ast_lock_type = type;
1519 }
1520
1521 enum AST_LOCK_RESULT ast_lock_path(const char *path)
1522 {
1523         enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
1524
1525         switch (ast_lock_type) {
1526         case AST_LOCK_TYPE_LOCKFILE:
1527                 r = ast_lock_path_lockfile(path);
1528                 break;
1529         case AST_LOCK_TYPE_FLOCK:
1530                 r = ast_lock_path_flock(path);
1531                 break;
1532         }
1533
1534         return r;
1535 }
1536
1537 int ast_unlock_path(const char *path)
1538 {
1539         int r = 0;
1540
1541         switch (ast_lock_type) {
1542         case AST_LOCK_TYPE_LOCKFILE:
1543                 r = ast_unlock_path_lockfile(path);
1544                 break;
1545         case AST_LOCK_TYPE_FLOCK:
1546                 r = ast_unlock_path_flock(path);
1547                 break;
1548         }
1549
1550         return r;
1551 }
1552
1553 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
1554 {
1555         int silencethreshold;
1556         int maxsilence = 0;
1557         int res = 0;
1558         int cmd = 0;
1559         int max_attempts = 3;
1560         int attempts = 0;
1561         int recorded = 0;
1562         int message_exists = 0;
1563         /* Note that urgent and private are for flagging messages as such in the future */
1564
1565         /* barf if no pointer passed to store duration in */
1566         if (!duration) {
1567                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1568                 return -1;
1569         }
1570
1571         cmd = '3';       /* Want to start by recording */
1572
1573         silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
1574
1575         while ((cmd >= 0) && (cmd != 't')) {
1576                 switch (cmd) {
1577                 case '1':
1578                         if (!message_exists) {
1579                                 /* In this case, 1 is to record a message */
1580                                 cmd = '3';
1581                                 break;
1582                         } else {
1583                                 ast_stream_and_wait(chan, "vm-msgsaved", "");
1584                                 cmd = 't';
1585                                 return res;
1586                         }
1587                 case '2':
1588                         /* Review */
1589                         ast_verb(3, "Reviewing the recording\n");
1590                         cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
1591                         break;
1592                 case '3':
1593                         message_exists = 0;
1594                         /* Record */
1595                         ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
1596                         recorded = 1;
1597                         if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
1598                                 /* User has hung up, no options to give */
1599                                 return cmd;
1600                         }
1601                         if (cmd == '0') {
1602                                 break;
1603                         } else if (cmd == '*') {
1604                                 break;
1605                         } else {
1606                                 /* If all is well, a message exists */
1607                                 message_exists = 1;
1608                                 cmd = 0;
1609                         }
1610                         break;
1611                 case '4':
1612                 case '5':
1613                 case '6':
1614                 case '7':
1615                 case '8':
1616                 case '9':
1617                 case '*':
1618                 case '#':
1619                         cmd = ast_play_and_wait(chan, "vm-sorry");
1620                         break;
1621                 default:
1622                         if (message_exists) {
1623                                 cmd = ast_play_and_wait(chan, "vm-review");
1624                         } else {
1625                                 if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
1626                                         cmd = ast_waitfordigit(chan, 600);
1627                                 }
1628                         }
1629
1630                         if (!cmd) {
1631                                 cmd = ast_waitfordigit(chan, 6000);
1632                         }
1633                         if (!cmd) {
1634                                 attempts++;
1635                         }
1636                         if (attempts > max_attempts) {
1637                                 cmd = 't';
1638                         }
1639                 }
1640         }
1641         if (cmd == 't') {
1642                 cmd = 0;
1643         }
1644         return cmd;
1645 }
1646
1647 #define RES_UPONE (1 << 16)
1648 #define RES_EXIT  (1 << 17)
1649 #define RES_REPEAT (1 << 18)
1650 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1651
1652 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1653
1654 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1655 {
1656         int res;
1657         int (*ivr_func)(struct ast_channel *, void *);
1658         char *c;
1659         char *n;
1660
1661         switch (option->action) {
1662         case AST_ACTION_UPONE:
1663                 return RES_UPONE;
1664         case AST_ACTION_EXIT:
1665                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1666         case AST_ACTION_REPEAT:
1667                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1668         case AST_ACTION_RESTART:
1669                 return RES_RESTART ;
1670         case AST_ACTION_NOOP:
1671                 return 0;
1672         case AST_ACTION_BACKGROUND:
1673                 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
1674                 if (res < 0) {
1675                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1676                         res = 0;
1677                 }
1678                 return res;
1679         case AST_ACTION_PLAYBACK:
1680                 res = ast_stream_and_wait(chan, (char *)option->adata, "");
1681                 if (res < 0) {
1682                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1683                         res = 0;
1684                 }
1685                 return res;
1686         case AST_ACTION_MENU:
1687                 if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
1688                         /* Do not pass entry errors back up, treat as though it was an "UPONE" */
1689                         res = 0;
1690                 }
1691                 return res;
1692         case AST_ACTION_WAITOPTION:
1693                 if (!(res = ast_waitfordigit(chan, chan->pbx ? chan->pbx->rtimeoutms : 10000))) {
1694                         return 't';
1695                 }
1696                 return res;
1697         case AST_ACTION_CALLBACK:
1698                 ivr_func = option->adata;
1699                 res = ivr_func(chan, cbdata);
1700                 return res;
1701         case AST_ACTION_TRANSFER:
1702                 res = ast_parseable_goto(chan, option->adata);
1703                 return 0;
1704         case AST_ACTION_PLAYLIST:
1705         case AST_ACTION_BACKLIST:
1706                 res = 0;
1707                 c = ast_strdupa(option->adata);
1708                 while ((n = strsep(&c, ";"))) {
1709                         if ((res = ast_stream_and_wait(chan, n,
1710                                         (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
1711                                 break;
1712                         }
1713                 }
1714                 ast_stopstream(chan);
1715                 return res;
1716         default:
1717                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1718                 return 0;
1719         }
1720         return -1;
1721 }
1722
1723 static int option_exists(struct ast_ivr_menu *menu, char *option)
1724 {
1725         int x;
1726         for (x = 0; menu->options[x].option; x++) {
1727                 if (!strcasecmp(menu->options[x].option, option)) {
1728                         return x;
1729                 }
1730         }
1731         return -1;
1732 }
1733
1734 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1735 {
1736         int x;
1737         for (x = 0; menu->options[x].option; x++) {
1738                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
1739                                 (menu->options[x].option[strlen(option)])) {
1740                         return x;
1741                 }
1742         }
1743         return -1;
1744 }
1745
1746 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1747 {
1748         int res = 0;
1749         int ms;
1750         while (option_matchmore(menu, exten)) {
1751                 ms = chan->pbx ? chan->pbx->dtimeoutms : 5000;
1752                 if (strlen(exten) >= maxexten - 1) {
1753                         break;
1754                 }
1755                 if ((res = ast_waitfordigit(chan, ms)) < 1) {
1756                         break;
1757                 }
1758                 exten[strlen(exten) + 1] = '\0';
1759                 exten[strlen(exten)] = res;
1760         }
1761         return res > 0 ? 0 : res;
1762 }
1763
1764 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1765 {
1766         /* Execute an IVR menu structure */
1767         int res = 0;
1768         int pos = 0;
1769         int retries = 0;
1770         char exten[AST_MAX_EXTENSION] = "s";
1771         if (option_exists(menu, "s") < 0) {
1772                 strcpy(exten, "g");
1773                 if (option_exists(menu, "g") < 0) {
1774                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1775                         return -1;
1776                 }
1777         }
1778         while (!res) {
1779                 while (menu->options[pos].option) {
1780                         if (!strcasecmp(menu->options[pos].option, exten)) {
1781                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1782                                 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1783                                 if (res < 0) {
1784                                         break;
1785                                 } else if (res & RES_UPONE) {
1786                                         return 0;
1787                                 } else if (res & RES_EXIT) {
1788                                         return res;
1789                                 } else if (res & RES_REPEAT) {
1790                                         int maxretries = res & 0xffff;
1791                                         if ((res & RES_RESTART) == RES_RESTART) {
1792                                                 retries = 0;
1793                                         } else {
1794                                                 retries++;
1795                                         }
1796                                         if (!maxretries) {
1797                                                 maxretries = 3;
1798                                         }
1799                                         if ((maxretries > 0) && (retries >= maxretries)) {
1800                                                 ast_debug(1, "Max retries %d exceeded\n", maxretries);
1801                                                 return -2;
1802                                         } else {
1803                                                 if (option_exists(menu, "g") > -1) {
1804                                                         strcpy(exten, "g");
1805                                                 } else if (option_exists(menu, "s") > -1) {
1806                                                         strcpy(exten, "s");
1807                                                 }
1808                                         }
1809                                         pos = 0;
1810                                         continue;
1811                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1812                                         ast_debug(1, "Got start of extension, %c\n", res);
1813                                         exten[1] = '\0';
1814                                         exten[0] = res;
1815                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
1816                                                 break;
1817                                         }
1818                                         if (option_exists(menu, exten) < 0) {
1819                                                 if (option_exists(menu, "i")) {
1820                                                         ast_debug(1, "Invalid extension entered, going to 'i'!\n");
1821                                                         strcpy(exten, "i");
1822                                                         pos = 0;
1823                                                         continue;
1824                                                 } else {
1825                                                         ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
1826                                                         res = -2;
1827                                                         break;
1828                                                 }
1829                                         } else {
1830                                                 ast_debug(1, "New existing extension: %s\n", exten);
1831                                                 pos = 0;
1832                                                 continue;
1833                                         }
1834                                 }
1835                         }
1836                         pos++;
1837                 }
1838                 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
1839                 pos = 0;
1840                 if (!strcasecmp(exten, "s")) {
1841                         strcpy(exten, "g");
1842                 } else {
1843                         break;
1844                 }
1845         }
1846         return res;
1847 }
1848
1849 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1850 {
1851         int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1852         /* Hide internal coding */
1853         return res > 0 ? 0 : res;
1854 }
1855
1856 char *ast_read_textfile(const char *filename)
1857 {
1858         int fd, count = 0, res;
1859         char *output = NULL;
1860         struct stat filesize;
1861
1862         if (stat(filename, &filesize) == -1) {
1863                 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
1864                 return NULL;
1865         }
1866
1867         count = filesize.st_size + 1;
1868
1869         if ((fd = open(filename, O_RDONLY)) < 0) {
1870                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1871                 return NULL;
1872         }
1873
1874         if ((output = ast_malloc(count))) {
1875                 res = read(fd, output, count - 1);
1876                 if (res == count - 1) {
1877                         output[res] = '\0';
1878                 } else {
1879                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
1880                         ast_free(output);
1881                         output = NULL;
1882                 }
1883         }
1884
1885         close(fd);
1886
1887         return output;
1888 }
1889
1890 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
1891 {
1892         char *s, *arg;
1893         int curarg, res = 0;
1894         unsigned int argloc;
1895         struct ast_flags *flags = _flags;
1896         struct ast_flags64 *flags64 = _flags;
1897
1898         if (flaglen == 32) {
1899                 ast_clear_flag(flags, AST_FLAGS_ALL);
1900         } else {
1901                 flags64->flags = 0;
1902         }
1903
1904         if (!optstr) {
1905                 return 0;
1906         }
1907
1908         s = optstr;
1909         while (*s) {
1910                 curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
1911                 argloc = options[curarg].arg_index;
1912                 if (*s == '(') {
1913                         int paren = 1, quote = 0;
1914                         int parsequotes = (s[1] == '"') ? 1 : 0;
1915
1916                         /* Has argument */
1917                         arg = ++s;
1918                         for (; *s; s++) {
1919                                 if (*s == '(' && !quote) {
1920                                         paren++;
1921                                 } else if (*s == ')' && !quote) {
1922                                         /* Count parentheses, unless they're within quotes (or backslashed, below) */
1923                                         paren--;
1924                                 } else if (*s == '"' && parsequotes) {
1925                                         /* Leave embedded quotes alone, unless they are the first character */
1926                                         quote = quote ? 0 : 1;
1927                                         ast_copy_string(s, s + 1, INT_MAX);
1928                                         s--;
1929                                 } else if (*s == '\\') {
1930                                         if (!quote) {
1931                                                 /* If a backslash is found outside of quotes, remove it */
1932                                                 ast_copy_string(s, s + 1, INT_MAX);
1933                                         } else if (quote && s[1] == '"') {
1934                                                 /* Backslash for a quote character within quotes, remove the backslash */
1935                                                 ast_copy_string(s, s + 1, INT_MAX);
1936                                         } else {
1937                                                 /* Backslash within quotes, keep both characters */
1938                                                 s++;
1939                                         }
1940                                 }
1941
1942                                 if (paren == 0) {
1943                                         break;
1944                                 }
1945                         }
1946                         /* This will find the closing paren we found above, or none, if the string ended before we found one. */
1947                         if ((s = strchr(s, ')'))) {
1948                                 if (argloc) {
1949                                         args[argloc - 1] = arg;
1950                                 }
1951                                 *s++ = '\0';
1952                         } else {
1953                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1954                                 res = -1;
1955                                 break;
1956                         }
1957                 } else if (argloc) {
1958                         args[argloc - 1] = "";
1959                 }
1960                 if (flaglen == 32) {
1961                         ast_set_flag(flags, options[curarg].flag);
1962                 } else {
1963                         ast_set_flag64(flags64, options[curarg].flag);
1964                 }
1965         }
1966
1967         return res;
1968 }
1969
1970 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1971 {
1972         return parse_options(options, flags, args, optstr, 32);
1973 }
1974
1975 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
1976 {
1977         return parse_options(options, flags, args, optstr, 64);
1978 }
1979
1980 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
1981 {
1982         unsigned int i, found = 0;
1983         for (i = 32; i < 128 && found < len; i++) {
1984                 if (ast_test_flag64(flags, options[i].flag)) {
1985                         buf[found++] = i;
1986                 }
1987         }
1988         buf[found] = '\0';
1989 }
1990
1991 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
1992 {
1993         int i;
1994         *consumed = 1;
1995         *result = 0;
1996         if (ast_strlen_zero(stream)) {
1997                 *consumed = 0;
1998                 return -1;
1999         }
2000
2001         if (*stream == '\\') {
2002                 *consumed = 2;
2003                 switch (*(stream + 1)) {
2004                 case 'n':
2005                         *result = '\n';
2006                         break;
2007                 case 'r':
2008                         *result = '\r';
2009                         break;
2010                 case 't':
2011                         *result = '\t';
2012                         break;
2013                 case 'x':
2014                         /* Hexadecimal */
2015                         if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
2016                                 *consumed = 3;
2017                                 if (*(stream + 2) <= '9') {
2018                                         *result = *(stream + 2) - '0';
2019                                 } else if (*(stream + 2) <= 'F') {
2020                                         *result = *(stream + 2) - 'A' + 10;
2021                                 } else {
2022                                         *result = *(stream + 2) - 'a' + 10;
2023                                 }
2024                         } else {
2025                                 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
2026                                 return -1;
2027                         }
2028
2029                         if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
2030                                 *consumed = 4;
2031                                 *result <<= 4;
2032                                 if (*(stream + 3) <= '9') {
2033                                         *result += *(stream + 3) - '0';
2034                                 } else if (*(stream + 3) <= 'F') {
2035                                         *result += *(stream + 3) - 'A' + 10;
2036                                 } else {
2037                                         *result += *(stream + 3) - 'a' + 10;
2038                                 }
2039                         }
2040                         break;
2041                 case '0':
2042                         /* Octal */
2043                         *consumed = 2;
2044                         for (i = 2; ; i++) {
2045                                 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
2046                                         (*consumed)++;
2047                                         ast_debug(5, "result was %d, ", *result);
2048                                         *result <<= 3;
2049                                         *result += *(stream + i) - '0';
2050                                         ast_debug(5, "is now %d\n", *result);
2051                                 } else {
2052                                         break;
2053                                 }
2054                         }
2055                         break;
2056                 default:
2057                         *result = *(stream + 1);
2058                 }
2059         } else {
2060                 *result = *stream;
2061                 *consumed = 1;
2062         }
2063         return 0;
2064 }
2065
2066 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
2067 {
2068         char *cur = result;
2069         size_t consumed;
2070
2071         while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
2072                 cur++;
2073                 stream += consumed;
2074         }
2075         *cur = '\0';
2076         return result;
2077 }
2078
2079 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
2080 {
2081         char next, *buf;
2082         size_t offset = 0;
2083         size_t consumed;
2084
2085         if (strchr(stream, '\\')) {
2086                 while (!ast_get_encoded_char(stream, &next, &consumed)) {
2087                         if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
2088                                 ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
2089                         }
2090                         if (offset + 2 > ast_str_size(*str)) {
2091                                 break;
2092                         }
2093                         buf = ast_str_buffer(*str);
2094                         buf[offset++] = next;
2095                         stream += consumed;
2096                 }
2097                 buf = ast_str_buffer(*str);
2098                 buf[offset++] = '\0';
2099                 ast_str_update(*str);
2100         } else {
2101                 ast_str_set(str, maxlen, "%s", stream);
2102         }
2103         return 0;
2104 }
2105
2106 void ast_close_fds_above_n(int n)
2107 {
2108         closefrom(n + 1);
2109 }
2110
2111 int ast_safe_fork(int stop_reaper)
2112 {
2113         sigset_t signal_set, old_set;
2114         int pid;
2115
2116         /* Don't let the default signal handler for children reap our status */
2117         if (stop_reaper) {
2118                 ast_replace_sigchld();
2119         }
2120
2121         sigfillset(&signal_set);
2122         pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
2123
2124         pid = fork();
2125
2126         if (pid != 0) {
2127                 /* Fork failed or parent */
2128                 pthread_sigmask(SIG_SETMASK, &old_set, NULL);
2129                 if (!stop_reaper && pid > 0) {
2130                         struct zombie *cur = ast_calloc(1, sizeof(*cur));
2131                         if (cur) {
2132                                 cur->pid = pid;
2133                                 AST_LIST_LOCK(&zombies);
2134                                 AST_LIST_INSERT_TAIL(&zombies, cur, list);
2135                                 AST_LIST_UNLOCK(&zombies);
2136                                 if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
2137                                         if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
2138                                                 ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
2139                                                 shaun_of_the_dead_thread = AST_PTHREADT_NULL;
2140                                         }
2141                                 }
2142                         }
2143                 }
2144                 return pid;
2145         } else {
2146                 /* Child */
2147 #ifdef HAVE_CAP
2148                 cap_t cap = cap_from_text("cap_net_admin-eip");
2149
2150                 if (cap_set_proc(cap)) {
2151                         ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
2152                 }
2153                 cap_free(cap);
2154 #endif
2155
2156                 /* Before we unblock our signals, return our trapped signals back to the defaults */
2157                 signal(SIGHUP, SIG_DFL);
2158                 signal(SIGCHLD, SIG_DFL);
2159                 signal(SIGINT, SIG_DFL);
2160                 signal(SIGURG, SIG_DFL);
2161                 signal(SIGTERM, SIG_DFL);
2162                 signal(SIGPIPE, SIG_DFL);
2163                 signal(SIGXFSZ, SIG_DFL);
2164
2165                 /* unblock important signal handlers */
2166                 if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
2167                         ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
2168                         _exit(1);
2169                 }
2170
2171                 return pid;
2172         }
2173 }
2174
2175 void ast_safe_fork_cleanup(void)
2176 {
2177         ast_unreplace_sigchld();
2178 }
2179
2180 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
2181 {
2182         int res;
2183         char u[10];
2184 #ifdef HAVE_LONG_DOUBLE_WIDER
2185         long double amount;
2186         #define FMT "%30Lf%9s"
2187 #else
2188         double amount;
2189         #define FMT "%30lf%9s"
2190 #endif
2191         if (!timestr) {
2192                 return -1;
2193         }
2194
2195         if ((res = sscanf(timestr, FMT, &amount, u)) == 0) {
2196 #undef FMT
2197                 return -1;
2198         } else if (res == 2) {
2199                 switch (u[0]) {
2200                 case 'h':
2201                 case 'H':
2202                         unit = TIMELEN_HOURS;
2203                         break;
2204                 case 's':
2205                 case 'S':
2206                         unit = TIMELEN_SECONDS;
2207                         break;
2208                 case 'm':
2209                 case 'M':
2210                         if (toupper(u[1]) == 'S') {
2211                                 unit = TIMELEN_MILLISECONDS;
2212                         } else if (u[1] == '\0') {
2213                                 unit = TIMELEN_MINUTES;
2214                         }
2215                         break;
2216                 }
2217         }
2218
2219         switch (unit) {
2220         case TIMELEN_HOURS:
2221                 amount *= 60;
2222                 /* fall-through */
2223         case TIMELEN_MINUTES:
2224                 amount *= 60;
2225                 /* fall-through */
2226         case TIMELEN_SECONDS:
2227                 amount *= 1000;
2228                 /* fall-through */
2229         case TIMELEN_MILLISECONDS:
2230                 ;
2231         }
2232         *result = amount > INT_MAX ? INT_MAX : (int) amount;
2233         return 0;
2234 }
2235