Add IPv6 to Asterisk.
[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, bracket = 0;
1194
1195         if (!array || !arraylen) {
1196                 return 0;
1197         }
1198
1199         memset(array, 0, arraylen * sizeof(*array));
1200
1201         if (!buf) {
1202                 return 0;
1203         }
1204
1205         scan = buf;
1206
1207         for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
1208                 array[argc] = scan;
1209                 for (; *scan; scan++) {
1210                         if (*scan == '(') {
1211                                 paren++;
1212                         } else if (*scan == ')') {
1213                                 if (paren) {
1214                                         paren--;
1215                                 }
1216                         } else if (*scan == '[') {
1217                                 bracket++;
1218                         } else if (*scan == ']') {
1219                                 if (bracket) {
1220                                         bracket--;
1221                                 }
1222                         } else if (*scan == '"' && delim != '"') {
1223                                 quote = quote ? 0 : 1;
1224                                 if (remove_chars) {
1225                                         /* Remove quote character from argument */
1226                                         memmove(scan, scan + 1, strlen(scan));
1227                                         scan--;
1228                                 }
1229                         } else if (*scan == '\\') {
1230                                 if (remove_chars) {
1231                                         /* Literal character, don't parse */
1232                                         memmove(scan, scan + 1, strlen(scan));
1233                                 } else {
1234                                         scan++;
1235                                 }
1236                         } else if ((*scan == delim) && !paren && !quote && !bracket) {
1237                                 wasdelim = scan;
1238                                 *scan++ = '\0';
1239                                 break;
1240                         }
1241                 }
1242         }
1243
1244         /* If the last character in the original string was the delimiter, then
1245          * there is one additional argument. */
1246         if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
1247                 array[argc++] = scan;
1248         }
1249
1250         return argc;
1251 }
1252
1253 /* ABI compatible function */
1254 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
1255 {
1256         return __ast_app_separate_args(buf, delim, 1, array, arraylen);
1257 }
1258
1259 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
1260 {
1261         char *s;
1262         char *fs;
1263         int res;
1264         int fd;
1265         int lp = strlen(path);
1266         time_t start;
1267
1268         s = alloca(lp + 10);
1269         fs = alloca(lp + 20);
1270
1271         snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
1272         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
1273         if (fd < 0) {
1274                 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
1275                 return AST_LOCK_PATH_NOT_FOUND;
1276         }
1277         close(fd);
1278
1279         snprintf(s, strlen(path) + 9, "%s/.lock", path);
1280         start = time(NULL);
1281         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
1282                 sched_yield();
1283         }
1284
1285         unlink(fs);
1286
1287         if (res) {
1288                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1289                 return AST_LOCK_TIMEOUT;
1290         } else {
1291                 ast_debug(1, "Locked path '%s'\n", path);
1292                 return AST_LOCK_SUCCESS;
1293         }
1294 }
1295
1296 static int ast_unlock_path_lockfile(const char *path)
1297 {
1298         char *s;
1299         int res;
1300
1301         s = alloca(strlen(path) + 10);
1302
1303         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1304
1305         if ((res = unlink(s))) {
1306                 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
1307         } else {
1308                 ast_debug(1, "Unlocked path '%s'\n", path);
1309         }
1310
1311         return res;
1312 }
1313
1314 struct path_lock {
1315         AST_LIST_ENTRY(path_lock) le;
1316         int fd;
1317         char *path;
1318 };
1319
1320 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
1321
1322 static void path_lock_destroy(struct path_lock *obj)
1323 {
1324         if (obj->fd >= 0) {
1325                 close(obj->fd);
1326         }
1327         if (obj->path) {
1328                 free(obj->path);
1329         }
1330         free(obj);
1331 }
1332
1333 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
1334 {
1335         char *fs;
1336         int res;
1337         int fd;
1338         time_t start;
1339         struct path_lock *pl;
1340         struct stat st, ost;
1341
1342         fs = alloca(strlen(path) + 20);
1343
1344         snprintf(fs, strlen(path) + 19, "%s/lock", path);
1345         if (lstat(fs, &st) == 0) {
1346                 if ((st.st_mode & S_IFMT) == S_IFLNK) {
1347                         ast_log(LOG_WARNING, "Unable to create lock file "
1348                                         "'%s': it's already a symbolic link\n",
1349                                         fs);
1350                         return AST_LOCK_FAILURE;
1351                 }
1352                 if (st.st_nlink > 1) {
1353                         ast_log(LOG_WARNING, "Unable to create lock file "
1354                                         "'%s': %u hard links exist\n",
1355                                         fs, (unsigned int) st.st_nlink);
1356                         return AST_LOCK_FAILURE;
1357                 }
1358         }
1359         if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
1360                 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
1361                                 fs, strerror(errno));
1362                 return AST_LOCK_PATH_NOT_FOUND;
1363         }
1364         if (!(pl = ast_calloc(1, sizeof(*pl)))) {
1365                 /* We don't unlink the lock file here, on the possibility that
1366                  * someone else created it - better to leave a little mess
1367                  * than create a big one by destroying someone else's lock
1368                  * and causing something to be corrupted.
1369                  */
1370                 close(fd);
1371                 return AST_LOCK_FAILURE;
1372         }
1373         pl->fd = fd;
1374         pl->path = strdup(path);
1375
1376         time(&start);
1377         while (
1378                 #ifdef SOLARIS
1379                 ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
1380                 #else
1381                 ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
1382                 #endif
1383                         (errno == EWOULDBLOCK) &&
1384                         (time(NULL) - start < 5))
1385                 usleep(1000);
1386         if (res) {
1387                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
1388                                 path, strerror(errno));
1389                 /* No unlinking of lock done, since we tried and failed to
1390                  * flock() it.
1391                  */
1392                 path_lock_destroy(pl);
1393                 return AST_LOCK_TIMEOUT;
1394         }
1395
1396         /* Check for the race where the file is recreated or deleted out from
1397          * underneath us.
1398          */
1399         if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
1400                         st.st_dev != ost.st_dev &&
1401                         st.st_ino != ost.st_ino) {
1402                 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
1403                                 "file changed underneath us\n", fs);
1404                 path_lock_destroy(pl);
1405                 return AST_LOCK_FAILURE;
1406         }
1407
1408         /* Success: file created, flocked, and is the one we started with */
1409         AST_LIST_LOCK(&path_lock_list);
1410         AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
1411         AST_LIST_UNLOCK(&path_lock_list);
1412
1413         ast_debug(1, "Locked path '%s'\n", path);
1414
1415         return AST_LOCK_SUCCESS;
1416 }
1417
1418 static int ast_unlock_path_flock(const char *path)
1419 {
1420         char *s;
1421         struct path_lock *p;
1422
1423         s = alloca(strlen(path) + 20);
1424
1425         AST_LIST_LOCK(&path_lock_list);
1426         AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
1427                 if (!strcmp(p->path, path)) {
1428                         AST_LIST_REMOVE_CURRENT(le);
1429                         break;
1430                 }
1431         }
1432         AST_LIST_TRAVERSE_SAFE_END;
1433         AST_LIST_UNLOCK(&path_lock_list);
1434
1435         if (p) {
1436                 snprintf(s, strlen(path) + 19, "%s/lock", path);
1437                 unlink(s);
1438                 path_lock_destroy(p);
1439                 ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
1440         } else {
1441                 ast_log(LOG_DEBUG, "Failed to unlock path '%s': "
1442                                 "lock not found\n", path);
1443         }
1444
1445         return 0;
1446 }
1447
1448 void ast_set_lock_type(enum AST_LOCK_TYPE type)
1449 {
1450         ast_lock_type = type;
1451 }
1452
1453 enum AST_LOCK_RESULT ast_lock_path(const char *path)
1454 {
1455         enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
1456
1457         switch (ast_lock_type) {
1458         case AST_LOCK_TYPE_LOCKFILE:
1459                 r = ast_lock_path_lockfile(path);
1460                 break;
1461         case AST_LOCK_TYPE_FLOCK:
1462                 r = ast_lock_path_flock(path);
1463                 break;
1464         }
1465
1466         return r;
1467 }
1468
1469 int ast_unlock_path(const char *path)
1470 {
1471         int r = 0;
1472
1473         switch (ast_lock_type) {
1474         case AST_LOCK_TYPE_LOCKFILE:
1475                 r = ast_unlock_path_lockfile(path);
1476                 break;
1477         case AST_LOCK_TYPE_FLOCK:
1478                 r = ast_unlock_path_flock(path);
1479                 break;
1480         }
1481
1482         return r;
1483 }
1484
1485 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
1486 {
1487         int silencethreshold;
1488         int maxsilence = 0;
1489         int res = 0;
1490         int cmd = 0;
1491         int max_attempts = 3;
1492         int attempts = 0;
1493         int recorded = 0;
1494         int message_exists = 0;
1495         /* Note that urgent and private are for flagging messages as such in the future */
1496
1497         /* barf if no pointer passed to store duration in */
1498         if (!duration) {
1499                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1500                 return -1;
1501         }
1502
1503         cmd = '3';       /* Want to start by recording */
1504
1505         silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
1506
1507         while ((cmd >= 0) && (cmd != 't')) {
1508                 switch (cmd) {
1509                 case '1':
1510                         if (!message_exists) {
1511                                 /* In this case, 1 is to record a message */
1512                                 cmd = '3';
1513                                 break;
1514                         } else {
1515                                 ast_stream_and_wait(chan, "vm-msgsaved", "");
1516                                 cmd = 't';
1517                                 return res;
1518                         }
1519                 case '2':
1520                         /* Review */
1521                         ast_verb(3, "Reviewing the recording\n");
1522                         cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
1523                         break;
1524                 case '3':
1525                         message_exists = 0;
1526                         /* Record */
1527                         ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
1528                         recorded = 1;
1529                         if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path)) == -1) {
1530                                 /* User has hung up, no options to give */
1531                                 return cmd;
1532                         }
1533                         if (cmd == '0') {
1534                                 break;
1535                         } else if (cmd == '*') {
1536                                 break;
1537                         } else {
1538                                 /* If all is well, a message exists */
1539                                 message_exists = 1;
1540                                 cmd = 0;
1541                         }
1542                         break;
1543                 case '4':
1544                 case '5':
1545                 case '6':
1546                 case '7':
1547                 case '8':
1548                 case '9':
1549                 case '*':
1550                 case '#':
1551                         cmd = ast_play_and_wait(chan, "vm-sorry");
1552                         break;
1553                 default:
1554                         if (message_exists) {
1555                                 cmd = ast_play_and_wait(chan, "vm-review");
1556                         } else {
1557                                 if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
1558                                         cmd = ast_waitfordigit(chan, 600);
1559                                 }
1560                         }
1561
1562                         if (!cmd) {
1563                                 cmd = ast_waitfordigit(chan, 6000);
1564                         }
1565                         if (!cmd) {
1566                                 attempts++;
1567                         }
1568                         if (attempts > max_attempts) {
1569                                 cmd = 't';
1570                         }
1571                 }
1572         }
1573         if (cmd == 't') {
1574                 cmd = 0;
1575         }
1576         return cmd;
1577 }
1578
1579 #define RES_UPONE (1 << 16)
1580 #define RES_EXIT  (1 << 17)
1581 #define RES_REPEAT (1 << 18)
1582 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1583
1584 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1585
1586 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1587 {
1588         int res;
1589         int (*ivr_func)(struct ast_channel *, void *);
1590         char *c;
1591         char *n;
1592
1593         switch (option->action) {
1594         case AST_ACTION_UPONE:
1595                 return RES_UPONE;
1596         case AST_ACTION_EXIT:
1597                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1598         case AST_ACTION_REPEAT:
1599                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1600         case AST_ACTION_RESTART:
1601                 return RES_RESTART ;
1602         case AST_ACTION_NOOP:
1603                 return 0;
1604         case AST_ACTION_BACKGROUND:
1605                 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
1606                 if (res < 0) {
1607                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1608                         res = 0;
1609                 }
1610                 return res;
1611         case AST_ACTION_PLAYBACK:
1612                 res = ast_stream_and_wait(chan, (char *)option->adata, "");
1613                 if (res < 0) {
1614                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1615                         res = 0;
1616                 }
1617                 return res;
1618         case AST_ACTION_MENU:
1619                 if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
1620                         /* Do not pass entry errors back up, treat as though it was an "UPONE" */
1621                         res = 0;
1622                 }
1623                 return res;
1624         case AST_ACTION_WAITOPTION:
1625                 if (!(res = ast_waitfordigit(chan, chan->pbx ? chan->pbx->rtimeoutms : 10000))) {
1626                         return 't';
1627                 }
1628                 return res;
1629         case AST_ACTION_CALLBACK:
1630                 ivr_func = option->adata;
1631                 res = ivr_func(chan, cbdata);
1632                 return res;
1633         case AST_ACTION_TRANSFER:
1634                 res = ast_parseable_goto(chan, option->adata);
1635                 return 0;
1636         case AST_ACTION_PLAYLIST:
1637         case AST_ACTION_BACKLIST:
1638                 res = 0;
1639                 c = ast_strdupa(option->adata);
1640                 while ((n = strsep(&c, ";"))) {
1641                         if ((res = ast_stream_and_wait(chan, n,
1642                                         (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
1643                                 break;
1644                         }
1645                 }
1646                 ast_stopstream(chan);
1647                 return res;
1648         default:
1649                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1650                 return 0;
1651         }
1652         return -1;
1653 }
1654
1655 static int option_exists(struct ast_ivr_menu *menu, char *option)
1656 {
1657         int x;
1658         for (x = 0; menu->options[x].option; x++) {
1659                 if (!strcasecmp(menu->options[x].option, option)) {
1660                         return x;
1661                 }
1662         }
1663         return -1;
1664 }
1665
1666 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1667 {
1668         int x;
1669         for (x = 0; menu->options[x].option; x++) {
1670                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
1671                                 (menu->options[x].option[strlen(option)])) {
1672                         return x;
1673                 }
1674         }
1675         return -1;
1676 }
1677
1678 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1679 {
1680         int res = 0;
1681         int ms;
1682         while (option_matchmore(menu, exten)) {
1683                 ms = chan->pbx ? chan->pbx->dtimeoutms : 5000;
1684                 if (strlen(exten) >= maxexten - 1) {
1685                         break;
1686                 }
1687                 if ((res = ast_waitfordigit(chan, ms)) < 1) {
1688                         break;
1689                 }
1690                 exten[strlen(exten) + 1] = '\0';
1691                 exten[strlen(exten)] = res;
1692         }
1693         return res > 0 ? 0 : res;
1694 }
1695
1696 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1697 {
1698         /* Execute an IVR menu structure */
1699         int res = 0;
1700         int pos = 0;
1701         int retries = 0;
1702         char exten[AST_MAX_EXTENSION] = "s";
1703         if (option_exists(menu, "s") < 0) {
1704                 strcpy(exten, "g");
1705                 if (option_exists(menu, "g") < 0) {
1706                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1707                         return -1;
1708                 }
1709         }
1710         while (!res) {
1711                 while (menu->options[pos].option) {
1712                         if (!strcasecmp(menu->options[pos].option, exten)) {
1713                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1714                                 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1715                                 if (res < 0) {
1716                                         break;
1717                                 } else if (res & RES_UPONE) {
1718                                         return 0;
1719                                 } else if (res & RES_EXIT) {
1720                                         return res;
1721                                 } else if (res & RES_REPEAT) {
1722                                         int maxretries = res & 0xffff;
1723                                         if ((res & RES_RESTART) == RES_RESTART) {
1724                                                 retries = 0;
1725                                         } else {
1726                                                 retries++;
1727                                         }
1728                                         if (!maxretries) {
1729                                                 maxretries = 3;
1730                                         }
1731                                         if ((maxretries > 0) && (retries >= maxretries)) {
1732                                                 ast_debug(1, "Max retries %d exceeded\n", maxretries);
1733                                                 return -2;
1734                                         } else {
1735                                                 if (option_exists(menu, "g") > -1) {
1736                                                         strcpy(exten, "g");
1737                                                 } else if (option_exists(menu, "s") > -1) {
1738                                                         strcpy(exten, "s");
1739                                                 }
1740                                         }
1741                                         pos = 0;
1742                                         continue;
1743                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1744                                         ast_debug(1, "Got start of extension, %c\n", res);
1745                                         exten[1] = '\0';
1746                                         exten[0] = res;
1747                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
1748                                                 break;
1749                                         }
1750                                         if (option_exists(menu, exten) < 0) {
1751                                                 if (option_exists(menu, "i")) {
1752                                                         ast_debug(1, "Invalid extension entered, going to 'i'!\n");
1753                                                         strcpy(exten, "i");
1754                                                         pos = 0;
1755                                                         continue;
1756                                                 } else {
1757                                                         ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
1758                                                         res = -2;
1759                                                         break;
1760                                                 }
1761                                         } else {
1762                                                 ast_debug(1, "New existing extension: %s\n", exten);
1763                                                 pos = 0;
1764                                                 continue;
1765                                         }
1766                                 }
1767                         }
1768                         pos++;
1769                 }
1770                 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
1771                 pos = 0;
1772                 if (!strcasecmp(exten, "s")) {
1773                         strcpy(exten, "g");
1774                 } else {
1775                         break;
1776                 }
1777         }
1778         return res;
1779 }
1780
1781 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1782 {
1783         int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1784         /* Hide internal coding */
1785         return res > 0 ? 0 : res;
1786 }
1787
1788 char *ast_read_textfile(const char *filename)
1789 {
1790         int fd, count = 0, res;
1791         char *output = NULL;
1792         struct stat filesize;
1793
1794         if (stat(filename, &filesize) == -1) {
1795                 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
1796                 return NULL;
1797         }
1798
1799         count = filesize.st_size + 1;
1800
1801         if ((fd = open(filename, O_RDONLY)) < 0) {
1802                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1803                 return NULL;
1804         }
1805
1806         if ((output = ast_malloc(count))) {
1807                 res = read(fd, output, count - 1);
1808                 if (res == count - 1) {
1809                         output[res] = '\0';
1810                 } else {
1811                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
1812                         ast_free(output);
1813                         output = NULL;
1814                 }
1815         }
1816
1817         close(fd);
1818
1819         return output;
1820 }
1821
1822 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
1823 {
1824         char *s, *arg;
1825         int curarg, res = 0;
1826         unsigned int argloc;
1827         struct ast_flags *flags = _flags;
1828         struct ast_flags64 *flags64 = _flags;
1829
1830         if (flaglen == 32) {
1831                 ast_clear_flag(flags, AST_FLAGS_ALL);
1832         } else {
1833                 flags64->flags = 0;
1834         }
1835
1836         if (!optstr) {
1837                 return 0;
1838         }
1839
1840         s = optstr;
1841         while (*s) {
1842                 curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
1843                 argloc = options[curarg].arg_index;
1844                 if (*s == '(') {
1845                         int paren = 1, quote = 0;
1846                         int parsequotes = (s[1] == '"') ? 1 : 0;
1847
1848                         /* Has argument */
1849                         arg = ++s;
1850                         for (; *s; s++) {
1851                                 if (*s == '(' && !quote) {
1852                                         paren++;
1853                                 } else if (*s == ')' && !quote) {
1854                                         /* Count parentheses, unless they're within quotes (or backslashed, below) */
1855                                         paren--;
1856                                 } else if (*s == '"' && parsequotes) {
1857                                         /* Leave embedded quotes alone, unless they are the first character */
1858                                         quote = quote ? 0 : 1;
1859                                         ast_copy_string(s, s + 1, INT_MAX);
1860                                         s--;
1861                                 } else if (*s == '\\') {
1862                                         if (!quote) {
1863                                                 /* If a backslash is found outside of quotes, remove it */
1864                                                 ast_copy_string(s, s + 1, INT_MAX);
1865                                         } else if (quote && s[1] == '"') {
1866                                                 /* Backslash for a quote character within quotes, remove the backslash */
1867                                                 ast_copy_string(s, s + 1, INT_MAX);
1868                                         } else {
1869                                                 /* Backslash within quotes, keep both characters */
1870                                                 s++;
1871                                         }
1872                                 }
1873
1874                                 if (paren == 0) {
1875                                         break;
1876                                 }
1877                         }
1878                         /* This will find the closing paren we found above, or none, if the string ended before we found one. */
1879                         if ((s = strchr(s, ')'))) {
1880                                 if (argloc) {
1881                                         args[argloc - 1] = arg;
1882                                 }
1883                                 *s++ = '\0';
1884                         } else {
1885                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1886                                 res = -1;
1887                                 break;
1888                         }
1889                 } else if (argloc) {
1890                         args[argloc - 1] = "";
1891                 }
1892                 if (flaglen == 32) {
1893                         ast_set_flag(flags, options[curarg].flag);
1894                 } else {
1895                         ast_set_flag64(flags64, options[curarg].flag);
1896                 }
1897         }
1898
1899         return res;
1900 }
1901
1902 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1903 {
1904         return parse_options(options, flags, args, optstr, 32);
1905 }
1906
1907 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
1908 {
1909         return parse_options(options, flags, args, optstr, 64);
1910 }
1911
1912 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
1913 {
1914         unsigned int i, found = 0;
1915         for (i = 32; i < 128 && found < len; i++) {
1916                 if (ast_test_flag64(flags, options[i].flag)) {
1917                         buf[found++] = i;
1918                 }
1919         }
1920         buf[found] = '\0';
1921 }
1922
1923 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
1924 {
1925         int i;
1926         *consumed = 1;
1927         *result = 0;
1928         if (ast_strlen_zero(stream)) {
1929                 *consumed = 0;
1930                 return -1;
1931         }
1932
1933         if (*stream == '\\') {
1934                 *consumed = 2;
1935                 switch (*(stream + 1)) {
1936                 case 'n':
1937                         *result = '\n';
1938                         break;
1939                 case 'r':
1940                         *result = '\r';
1941                         break;
1942                 case 't':
1943                         *result = '\t';
1944                         break;
1945                 case 'x':
1946                         /* Hexadecimal */
1947                         if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
1948                                 *consumed = 3;
1949                                 if (*(stream + 2) <= '9') {
1950                                         *result = *(stream + 2) - '0';
1951                                 } else if (*(stream + 2) <= 'F') {
1952                                         *result = *(stream + 2) - 'A' + 10;
1953                                 } else {
1954                                         *result = *(stream + 2) - 'a' + 10;
1955                                 }
1956                         } else {
1957                                 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
1958                                 return -1;
1959                         }
1960
1961                         if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
1962                                 *consumed = 4;
1963                                 *result <<= 4;
1964                                 if (*(stream + 3) <= '9') {
1965                                         *result += *(stream + 3) - '0';
1966                                 } else if (*(stream + 3) <= 'F') {
1967                                         *result += *(stream + 3) - 'A' + 10;
1968                                 } else {
1969                                         *result += *(stream + 3) - 'a' + 10;
1970                                 }
1971                         }
1972                         break;
1973                 case '0':
1974                         /* Octal */
1975                         *consumed = 2;
1976                         for (i = 2; ; i++) {
1977                                 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
1978                                         (*consumed)++;
1979                                         ast_debug(5, "result was %d, ", *result);
1980                                         *result <<= 3;
1981                                         *result += *(stream + i) - '0';
1982                                         ast_debug(5, "is now %d\n", *result);
1983                                 } else {
1984                                         break;
1985                                 }
1986                         }
1987                         break;
1988                 default:
1989                         *result = *(stream + 1);
1990                 }
1991         } else {
1992                 *result = *stream;
1993                 *consumed = 1;
1994         }
1995         return 0;
1996 }
1997
1998 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
1999 {
2000         char *cur = result;
2001         size_t consumed;
2002
2003         while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
2004                 cur++;
2005                 stream += consumed;
2006         }
2007         *cur = '\0';
2008         return result;
2009 }
2010
2011 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
2012 {
2013         char next, *buf;
2014         size_t offset = 0;
2015         size_t consumed;
2016
2017         if (strchr(stream, '\\')) {
2018                 while (!ast_get_encoded_char(stream, &next, &consumed)) {
2019                         if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
2020                                 ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
2021                         }
2022                         if (offset + 2 > ast_str_size(*str)) {
2023                                 break;
2024                         }
2025                         buf = ast_str_buffer(*str);
2026                         buf[offset++] = next;
2027                         stream += consumed;
2028                 }
2029                 buf = ast_str_buffer(*str);
2030                 buf[offset++] = '\0';
2031                 ast_str_update(*str);
2032         } else {
2033                 ast_str_set(str, maxlen, "%s", stream);
2034         }
2035         return 0;
2036 }
2037
2038 void ast_close_fds_above_n(int n)
2039 {
2040         closefrom(n + 1);
2041 }
2042
2043 int ast_safe_fork(int stop_reaper)
2044 {
2045         sigset_t signal_set, old_set;
2046         int pid;
2047
2048         /* Don't let the default signal handler for children reap our status */
2049         if (stop_reaper) {
2050                 ast_replace_sigchld();
2051         }
2052
2053         sigfillset(&signal_set);
2054         pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
2055
2056         pid = fork();
2057
2058         if (pid != 0) {
2059                 /* Fork failed or parent */
2060                 pthread_sigmask(SIG_SETMASK, &old_set, NULL);
2061                 return pid;
2062         } else {
2063                 /* Child */
2064 #ifdef HAVE_CAP
2065                 cap_t cap = cap_from_text("cap_net_admin-eip");
2066
2067                 if (cap_set_proc(cap)) {
2068                         ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
2069                 }
2070                 cap_free(cap);
2071 #endif
2072
2073                 /* Before we unblock our signals, return our trapped signals back to the defaults */
2074                 signal(SIGHUP, SIG_DFL);
2075                 signal(SIGCHLD, SIG_DFL);
2076                 signal(SIGINT, SIG_DFL);
2077                 signal(SIGURG, SIG_DFL);
2078                 signal(SIGTERM, SIG_DFL);
2079                 signal(SIGPIPE, SIG_DFL);
2080                 signal(SIGXFSZ, SIG_DFL);
2081
2082                 /* unblock important signal handlers */
2083                 if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
2084                         ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
2085                         _exit(1);
2086                 }
2087
2088                 return pid;
2089         }
2090 }
2091
2092 void ast_safe_fork_cleanup(void)
2093 {
2094         ast_unreplace_sigchld();
2095 }
2096
2097 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
2098 {
2099         int res;
2100         char u[10];
2101 #ifdef HAVE_LONG_DOUBLE_WIDER
2102         long double amount;
2103         #define FMT "%30Lf%9s"
2104 #else
2105         double amount;
2106         #define FMT "%30lf%9s"
2107 #endif
2108         if (!timestr) {
2109                 return -1;
2110         }
2111
2112         if ((res = sscanf(timestr, FMT, &amount, u)) == 0) {
2113 #undef FMT
2114                 return -1;
2115         } else if (res == 2) {
2116                 switch (u[0]) {
2117                 case 'h':
2118                 case 'H':
2119                         unit = TIMELEN_HOURS;
2120                         break;
2121                 case 's':
2122                 case 'S':
2123                         unit = TIMELEN_SECONDS;
2124                         break;
2125                 case 'm':
2126                 case 'M':
2127                         if (toupper(u[1]) == 'S') {
2128                                 unit = TIMELEN_MILLISECONDS;
2129                         } else if (u[1] == '\0') {
2130                                 unit = TIMELEN_MINUTES;
2131                         }
2132                         break;
2133                 }
2134         }
2135
2136         switch (unit) {
2137         case TIMELEN_HOURS:
2138                 amount *= 60;
2139                 /* fall-through */
2140         case TIMELEN_MINUTES:
2141                 amount *= 60;
2142                 /* fall-through */
2143         case TIMELEN_SECONDS:
2144                 amount *= 1000;
2145                 /* fall-through */
2146         case TIMELEN_MILLISECONDS:
2147                 ;
2148         }
2149         *result = amount > INT_MAX ? INT_MAX : (int) amount;
2150         return 0;
2151 }
2152