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