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