ast_callerid restructuring
[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                 if (*duration < 0) {
920                         *duration = 0;
921                 }
922                 for (x = 0; x < fmtcnt; x++) {
923                         if (!others[x]) {
924                                 break;
925                         }
926                         /*!\note
927                          * If we ended with silence, trim all but the first 200ms of silence
928                          * off the recording.  However, if we ended with '#', we don't want
929                          * to trim ANY part of the recording.
930                          */
931                         if (res > 0 && dspsilence) {
932                                 /* rewind only the trailing silence */
933                                 ast_stream_rewind(others[x], dspsilence - 200);
934                         }
935                         ast_truncstream(others[x]);
936                         ast_closestream(others[x]);
937                 }
938         }
939
940         if (prepend && outmsg) {
941                 struct ast_filestream *realfiles[AST_MAX_FORMATS];
942                 struct ast_frame *fr;
943
944                 for (x = 0; x < fmtcnt; x++) {
945                         snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
946                         realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
947                         if (!others[x] || !realfiles[x]) {
948                                 break;
949                         }
950                         /*!\note Same logic as above. */
951                         if (dspsilence) {
952                                 ast_stream_rewind(others[x], dspsilence - 200);
953                         }
954                         ast_truncstream(others[x]);
955                         /* add the original file too */
956                         while ((fr = ast_readframe(realfiles[x]))) {
957                                 ast_writestream(others[x], fr);
958                                 ast_frfree(fr);
959                         }
960                         ast_closestream(others[x]);
961                         ast_closestream(realfiles[x]);
962                         ast_filerename(prependfile, recordfile, sfmt[x]);
963                         ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
964                         ast_filedelete(prependfile, sfmt[x]);
965                 }
966         }
967         if (rfmt && ast_set_read_format(chan, rfmt)) {
968                 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
969         }
970         if (outmsg == 2) {
971                 ast_stream_and_wait(chan, "auth-thankyou", "");
972         }
973         if (sildet) {
974                 ast_dsp_free(sildet);
975         }
976         return res;
977 }
978
979 static const char default_acceptdtmf[] = "#";
980 static const char default_canceldtmf[] = "";
981
982 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)
983 {
984         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));
985 }
986
987 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)
988 {
989         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf);
990 }
991
992 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)
993 {
994         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf);
995 }
996
997 /* Channel group core functions */
998
999 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
1000 {
1001         int res = 0;
1002         char tmp[256];
1003         char *grp = NULL, *cat = NULL;
1004
1005         if (!ast_strlen_zero(data)) {
1006                 ast_copy_string(tmp, data, sizeof(tmp));
1007                 grp = tmp;
1008                 if ((cat = strchr(tmp, '@'))) {
1009                         *cat++ = '\0';
1010                 }
1011         }
1012
1013         if (!ast_strlen_zero(grp)) {
1014                 ast_copy_string(group, grp, group_max);
1015         } else {
1016                 *group = '\0';
1017         }
1018
1019         if (!ast_strlen_zero(cat)) {
1020                 ast_copy_string(category, cat, category_max);
1021         }
1022
1023         return res;
1024 }
1025
1026 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
1027 {
1028         int res = 0;
1029         char group[80] = "", category[80] = "";
1030         struct ast_group_info *gi = NULL;
1031         size_t len = 0;
1032
1033         if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
1034                 return -1;
1035         }
1036
1037         /* Calculate memory we will need if this is new */
1038         len = sizeof(*gi) + strlen(group) + 1;
1039         if (!ast_strlen_zero(category)) {
1040                 len += strlen(category) + 1;
1041         }
1042
1043         AST_RWLIST_WRLOCK(&groups);
1044         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1045                 if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1046                         AST_RWLIST_REMOVE_CURRENT(group_list);
1047                         free(gi);
1048                         break;
1049                 }
1050         }
1051         AST_RWLIST_TRAVERSE_SAFE_END;
1052
1053         if (ast_strlen_zero(group)) {
1054                 /* Enable unsetting the group */
1055         } else if ((gi = calloc(1, len))) {
1056                 gi->chan = chan;
1057                 gi->group = (char *) gi + sizeof(*gi);
1058                 strcpy(gi->group, group);
1059                 if (!ast_strlen_zero(category)) {
1060                         gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
1061                         strcpy(gi->category, category);
1062                 }
1063                 AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
1064         } else {
1065                 res = -1;
1066         }
1067
1068         AST_RWLIST_UNLOCK(&groups);
1069
1070         return res;
1071 }
1072
1073 int ast_app_group_get_count(const char *group, const char *category)
1074 {
1075         struct ast_group_info *gi = NULL;
1076         int count = 0;
1077
1078         if (ast_strlen_zero(group)) {
1079                 return 0;
1080         }
1081
1082         AST_RWLIST_RDLOCK(&groups);
1083         AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1084                 if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
1085                         count++;
1086                 }
1087         }
1088         AST_RWLIST_UNLOCK(&groups);
1089
1090         return count;
1091 }
1092
1093 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
1094 {
1095         struct ast_group_info *gi = NULL;
1096         regex_t regexbuf_group;
1097         regex_t regexbuf_category;
1098         int count = 0;
1099
1100         if (ast_strlen_zero(groupmatch)) {
1101                 ast_log(LOG_NOTICE, "groupmatch empty\n");
1102                 return 0;
1103         }
1104
1105         /* if regex compilation fails, return zero matches */
1106         if (regcomp(&regexbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
1107                 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
1108                 return 0;
1109         }
1110
1111         if (!ast_strlen_zero(category) && regcomp(&regexbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
1112                 ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
1113                 return 0;
1114         }
1115
1116         AST_RWLIST_RDLOCK(&groups);
1117         AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
1118                 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)))) {
1119                         count++;
1120                 }
1121         }
1122         AST_RWLIST_UNLOCK(&groups);
1123
1124         regfree(&regexbuf_group);
1125         if (!ast_strlen_zero(category)) {
1126                 regfree(&regexbuf_category);
1127         }
1128
1129         return count;
1130 }
1131
1132 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
1133 {
1134         struct ast_group_info *gi = NULL;
1135
1136         AST_RWLIST_WRLOCK(&groups);
1137         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1138                 if (gi->chan == old) {
1139                         gi->chan = new;
1140                 } else if (gi->chan == new) {
1141                         AST_RWLIST_REMOVE_CURRENT(group_list);
1142                         ast_free(gi);
1143                 }
1144         }
1145         AST_RWLIST_TRAVERSE_SAFE_END;
1146         AST_RWLIST_UNLOCK(&groups);
1147
1148         return 0;
1149 }
1150
1151 int ast_app_group_discard(struct ast_channel *chan)
1152 {
1153         struct ast_group_info *gi = NULL;
1154
1155         AST_RWLIST_WRLOCK(&groups);
1156         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
1157                 if (gi->chan == chan) {
1158                         AST_RWLIST_REMOVE_CURRENT(group_list);
1159                         ast_free(gi);
1160                 }
1161         }
1162         AST_RWLIST_TRAVERSE_SAFE_END;
1163         AST_RWLIST_UNLOCK(&groups);
1164
1165         return 0;
1166 }
1167
1168 int ast_app_group_list_wrlock(void)
1169 {
1170         return AST_RWLIST_WRLOCK(&groups);
1171 }
1172
1173 int ast_app_group_list_rdlock(void)
1174 {
1175         return AST_RWLIST_RDLOCK(&groups);
1176 }
1177
1178 struct ast_group_info *ast_app_group_list_head(void)
1179 {
1180         return AST_RWLIST_FIRST(&groups);
1181 }
1182
1183 int ast_app_group_list_unlock(void)
1184 {
1185         return AST_RWLIST_UNLOCK(&groups);
1186 }
1187
1188 #undef ast_app_separate_args
1189 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
1190
1191 unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
1192 {
1193         int argc;
1194         char *scan, *wasdelim = NULL;
1195         int paren = 0, quote = 0, bracket = 0;
1196
1197         if (!array || !arraylen) {
1198                 return 0;
1199         }
1200
1201         memset(array, 0, arraylen * sizeof(*array));
1202
1203         if (!buf) {
1204                 return 0;
1205         }
1206
1207         scan = buf;
1208
1209         for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
1210                 array[argc] = scan;
1211                 for (; *scan; scan++) {
1212                         if (*scan == '(') {
1213                                 paren++;
1214                         } else if (*scan == ')') {
1215                                 if (paren) {
1216                                         paren--;
1217                                 }
1218                         } else if (*scan == '[') {
1219                                 bracket++;
1220                         } else if (*scan == ']') {
1221                                 if (bracket) {
1222                                         bracket--;
1223                                 }
1224                         } else if (*scan == '"' && delim != '"') {
1225                                 quote = quote ? 0 : 1;
1226                                 if (remove_chars) {
1227                                         /* Remove quote character from argument */
1228                                         memmove(scan, scan + 1, strlen(scan));
1229                                         scan--;
1230                                 }
1231                         } else if (*scan == '\\') {
1232                                 if (remove_chars) {
1233                                         /* Literal character, don't parse */
1234                                         memmove(scan, scan + 1, strlen(scan));
1235                                 } else {
1236                                         scan++;
1237                                 }
1238                         } else if ((*scan == delim) && !paren && !quote && !bracket) {
1239                                 wasdelim = scan;
1240                                 *scan++ = '\0';
1241                                 break;
1242                         }
1243                 }
1244         }
1245
1246         /* If the last character in the original string was the delimiter, then
1247          * there is one additional argument. */
1248         if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
1249                 array[argc++] = scan;
1250         }
1251
1252         return argc;
1253 }
1254
1255 /* ABI compatible function */
1256 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
1257 {
1258         return __ast_app_separate_args(buf, delim, 1, array, arraylen);
1259 }
1260
1261 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
1262 {
1263         char *s;
1264         char *fs;
1265         int res;
1266         int fd;
1267         int lp = strlen(path);
1268         time_t start;
1269
1270         s = alloca(lp + 10);
1271         fs = alloca(lp + 20);
1272
1273         snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
1274         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
1275         if (fd < 0) {
1276                 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
1277                 return AST_LOCK_PATH_NOT_FOUND;
1278         }
1279         close(fd);
1280
1281         snprintf(s, strlen(path) + 9, "%s/.lock", path);
1282         start = time(NULL);
1283         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
1284                 sched_yield();
1285         }
1286
1287         unlink(fs);
1288
1289         if (res) {
1290                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
1291                 return AST_LOCK_TIMEOUT;
1292         } else {
1293                 ast_debug(1, "Locked path '%s'\n", path);
1294                 return AST_LOCK_SUCCESS;
1295         }
1296 }
1297
1298 static int ast_unlock_path_lockfile(const char *path)
1299 {
1300         char *s;
1301         int res;
1302
1303         s = alloca(strlen(path) + 10);
1304
1305         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
1306
1307         if ((res = unlink(s))) {
1308                 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
1309         } else {
1310                 ast_debug(1, "Unlocked path '%s'\n", path);
1311         }
1312
1313         return res;
1314 }
1315
1316 struct path_lock {
1317         AST_LIST_ENTRY(path_lock) le;
1318         int fd;
1319         char *path;
1320 };
1321
1322 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
1323
1324 static void path_lock_destroy(struct path_lock *obj)
1325 {
1326         if (obj->fd >= 0) {
1327                 close(obj->fd);
1328         }
1329         if (obj->path) {
1330                 free(obj->path);
1331         }
1332         free(obj);
1333 }
1334
1335 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
1336 {
1337         char *fs;
1338         int res;
1339         int fd;
1340         time_t start;
1341         struct path_lock *pl;
1342         struct stat st, ost;
1343
1344         fs = alloca(strlen(path) + 20);
1345
1346         snprintf(fs, strlen(path) + 19, "%s/lock", path);
1347         if (lstat(fs, &st) == 0) {
1348                 if ((st.st_mode & S_IFMT) == S_IFLNK) {
1349                         ast_log(LOG_WARNING, "Unable to create lock file "
1350                                         "'%s': it's already a symbolic link\n",
1351                                         fs);
1352                         return AST_LOCK_FAILURE;
1353                 }
1354                 if (st.st_nlink > 1) {
1355                         ast_log(LOG_WARNING, "Unable to create lock file "
1356                                         "'%s': %u hard links exist\n",
1357                                         fs, (unsigned int) st.st_nlink);
1358                         return AST_LOCK_FAILURE;
1359                 }
1360         }
1361         if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
1362                 ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
1363                                 fs, strerror(errno));
1364                 return AST_LOCK_PATH_NOT_FOUND;
1365         }
1366         if (!(pl = ast_calloc(1, sizeof(*pl)))) {
1367                 /* We don't unlink the lock file here, on the possibility that
1368                  * someone else created it - better to leave a little mess
1369                  * than create a big one by destroying someone else's lock
1370                  * and causing something to be corrupted.
1371                  */
1372                 close(fd);
1373                 return AST_LOCK_FAILURE;
1374         }
1375         pl->fd = fd;
1376         pl->path = strdup(path);
1377
1378         time(&start);
1379         while (
1380                 #ifdef SOLARIS
1381                 ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
1382                 #else
1383                 ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
1384                 #endif
1385                         (errno == EWOULDBLOCK) &&
1386                         (time(NULL) - start < 5))
1387                 usleep(1000);
1388         if (res) {
1389                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
1390                                 path, strerror(errno));
1391                 /* No unlinking of lock done, since we tried and failed to
1392                  * flock() it.
1393                  */
1394                 path_lock_destroy(pl);
1395                 return AST_LOCK_TIMEOUT;
1396         }
1397
1398         /* Check for the race where the file is recreated or deleted out from
1399          * underneath us.
1400          */
1401         if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
1402                         st.st_dev != ost.st_dev &&
1403                         st.st_ino != ost.st_ino) {
1404                 ast_log(LOG_WARNING, "Unable to create lock file '%s': "
1405                                 "file changed underneath us\n", fs);
1406                 path_lock_destroy(pl);
1407                 return AST_LOCK_FAILURE;
1408         }
1409
1410         /* Success: file created, flocked, and is the one we started with */
1411         AST_LIST_LOCK(&path_lock_list);
1412         AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
1413         AST_LIST_UNLOCK(&path_lock_list);
1414
1415         ast_debug(1, "Locked path '%s'\n", path);
1416
1417         return AST_LOCK_SUCCESS;
1418 }
1419
1420 static int ast_unlock_path_flock(const char *path)
1421 {
1422         char *s;
1423         struct path_lock *p;
1424
1425         s = alloca(strlen(path) + 20);
1426
1427         AST_LIST_LOCK(&path_lock_list);
1428         AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
1429                 if (!strcmp(p->path, path)) {
1430                         AST_LIST_REMOVE_CURRENT(le);
1431                         break;
1432                 }
1433         }
1434         AST_LIST_TRAVERSE_SAFE_END;
1435         AST_LIST_UNLOCK(&path_lock_list);
1436
1437         if (p) {
1438                 snprintf(s, strlen(path) + 19, "%s/lock", path);
1439                 unlink(s);
1440                 path_lock_destroy(p);
1441                 ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
1442         } else {
1443                 ast_log(LOG_DEBUG, "Failed to unlock path '%s': "
1444                                 "lock not found\n", path);
1445         }
1446
1447         return 0;
1448 }
1449
1450 void ast_set_lock_type(enum AST_LOCK_TYPE type)
1451 {
1452         ast_lock_type = type;
1453 }
1454
1455 enum AST_LOCK_RESULT ast_lock_path(const char *path)
1456 {
1457         enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
1458
1459         switch (ast_lock_type) {
1460         case AST_LOCK_TYPE_LOCKFILE:
1461                 r = ast_lock_path_lockfile(path);
1462                 break;
1463         case AST_LOCK_TYPE_FLOCK:
1464                 r = ast_lock_path_flock(path);
1465                 break;
1466         }
1467
1468         return r;
1469 }
1470
1471 int ast_unlock_path(const char *path)
1472 {
1473         int r = 0;
1474
1475         switch (ast_lock_type) {
1476         case AST_LOCK_TYPE_LOCKFILE:
1477                 r = ast_unlock_path_lockfile(path);
1478                 break;
1479         case AST_LOCK_TYPE_FLOCK:
1480                 r = ast_unlock_path_flock(path);
1481                 break;
1482         }
1483
1484         return r;
1485 }
1486
1487 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
1488 {
1489         int silencethreshold;
1490         int maxsilence = 0;
1491         int res = 0;
1492         int cmd = 0;
1493         int max_attempts = 3;
1494         int attempts = 0;
1495         int recorded = 0;
1496         int message_exists = 0;
1497         /* Note that urgent and private are for flagging messages as such in the future */
1498
1499         /* barf if no pointer passed to store duration in */
1500         if (!duration) {
1501                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1502                 return -1;
1503         }
1504
1505         cmd = '3';       /* Want to start by recording */
1506
1507         silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
1508
1509         while ((cmd >= 0) && (cmd != 't')) {
1510                 switch (cmd) {
1511                 case '1':
1512                         if (!message_exists) {
1513                                 /* In this case, 1 is to record a message */
1514                                 cmd = '3';
1515                                 break;
1516                         } else {
1517                                 ast_stream_and_wait(chan, "vm-msgsaved", "");
1518                                 cmd = 't';
1519                                 return res;
1520                         }
1521                 case '2':
1522                         /* Review */
1523                         ast_verb(3, "Reviewing the recording\n");
1524                         cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
1525                         break;
1526                 case '3':
1527                         message_exists = 0;
1528                         /* Record */
1529                         ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
1530                         recorded = 1;
1531                         if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path)) == -1) {
1532                                 /* User has hung up, no options to give */
1533                                 return cmd;
1534                         }
1535                         if (cmd == '0') {
1536                                 break;
1537                         } else if (cmd == '*') {
1538                                 break;
1539                         } else {
1540                                 /* If all is well, a message exists */
1541                                 message_exists = 1;
1542                                 cmd = 0;
1543                         }
1544                         break;
1545                 case '4':
1546                 case '5':
1547                 case '6':
1548                 case '7':
1549                 case '8':
1550                 case '9':
1551                 case '*':
1552                 case '#':
1553                         cmd = ast_play_and_wait(chan, "vm-sorry");
1554                         break;
1555                 default:
1556                         if (message_exists) {
1557                                 cmd = ast_play_and_wait(chan, "vm-review");
1558                         } else {
1559                                 if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
1560                                         cmd = ast_waitfordigit(chan, 600);
1561                                 }
1562                         }
1563
1564                         if (!cmd) {
1565                                 cmd = ast_waitfordigit(chan, 6000);
1566                         }
1567                         if (!cmd) {
1568                                 attempts++;
1569                         }
1570                         if (attempts > max_attempts) {
1571                                 cmd = 't';
1572                         }
1573                 }
1574         }
1575         if (cmd == 't') {
1576                 cmd = 0;
1577         }
1578         return cmd;
1579 }
1580
1581 #define RES_UPONE (1 << 16)
1582 #define RES_EXIT  (1 << 17)
1583 #define RES_REPEAT (1 << 18)
1584 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1585
1586 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1587
1588 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1589 {
1590         int res;
1591         int (*ivr_func)(struct ast_channel *, void *);
1592         char *c;
1593         char *n;
1594
1595         switch (option->action) {
1596         case AST_ACTION_UPONE:
1597                 return RES_UPONE;
1598         case AST_ACTION_EXIT:
1599                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1600         case AST_ACTION_REPEAT:
1601                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1602         case AST_ACTION_RESTART:
1603                 return RES_RESTART ;
1604         case AST_ACTION_NOOP:
1605                 return 0;
1606         case AST_ACTION_BACKGROUND:
1607                 res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
1608                 if (res < 0) {
1609                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1610                         res = 0;
1611                 }
1612                 return res;
1613         case AST_ACTION_PLAYBACK:
1614                 res = ast_stream_and_wait(chan, (char *)option->adata, "");
1615                 if (res < 0) {
1616                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1617                         res = 0;
1618                 }
1619                 return res;
1620         case AST_ACTION_MENU:
1621                 if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
1622                         /* Do not pass entry errors back up, treat as though it was an "UPONE" */
1623                         res = 0;
1624                 }
1625                 return res;
1626         case AST_ACTION_WAITOPTION:
1627                 if (!(res = ast_waitfordigit(chan, chan->pbx ? chan->pbx->rtimeoutms : 10000))) {
1628                         return 't';
1629                 }
1630                 return res;
1631         case AST_ACTION_CALLBACK:
1632                 ivr_func = option->adata;
1633                 res = ivr_func(chan, cbdata);
1634                 return res;
1635         case AST_ACTION_TRANSFER:
1636                 res = ast_parseable_goto(chan, option->adata);
1637                 return 0;
1638         case AST_ACTION_PLAYLIST:
1639         case AST_ACTION_BACKLIST:
1640                 res = 0;
1641                 c = ast_strdupa(option->adata);
1642                 while ((n = strsep(&c, ";"))) {
1643                         if ((res = ast_stream_and_wait(chan, n,
1644                                         (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
1645                                 break;
1646                         }
1647                 }
1648                 ast_stopstream(chan);
1649                 return res;
1650         default:
1651                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1652                 return 0;
1653         }
1654         return -1;
1655 }
1656
1657 static int option_exists(struct ast_ivr_menu *menu, char *option)
1658 {
1659         int x;
1660         for (x = 0; menu->options[x].option; x++) {
1661                 if (!strcasecmp(menu->options[x].option, option)) {
1662                         return x;
1663                 }
1664         }
1665         return -1;
1666 }
1667
1668 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1669 {
1670         int x;
1671         for (x = 0; menu->options[x].option; x++) {
1672                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
1673                                 (menu->options[x].option[strlen(option)])) {
1674                         return x;
1675                 }
1676         }
1677         return -1;
1678 }
1679
1680 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1681 {
1682         int res = 0;
1683         int ms;
1684         while (option_matchmore(menu, exten)) {
1685                 ms = chan->pbx ? chan->pbx->dtimeoutms : 5000;
1686                 if (strlen(exten) >= maxexten - 1) {
1687                         break;
1688                 }
1689                 if ((res = ast_waitfordigit(chan, ms)) < 1) {
1690                         break;
1691                 }
1692                 exten[strlen(exten) + 1] = '\0';
1693                 exten[strlen(exten)] = res;
1694         }
1695         return res > 0 ? 0 : res;
1696 }
1697
1698 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1699 {
1700         /* Execute an IVR menu structure */
1701         int res = 0;
1702         int pos = 0;
1703         int retries = 0;
1704         char exten[AST_MAX_EXTENSION] = "s";
1705         if (option_exists(menu, "s") < 0) {
1706                 strcpy(exten, "g");
1707                 if (option_exists(menu, "g") < 0) {
1708                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1709                         return -1;
1710                 }
1711         }
1712         while (!res) {
1713                 while (menu->options[pos].option) {
1714                         if (!strcasecmp(menu->options[pos].option, exten)) {
1715                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1716                                 ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1717                                 if (res < 0) {
1718                                         break;
1719                                 } else if (res & RES_UPONE) {
1720                                         return 0;
1721                                 } else if (res & RES_EXIT) {
1722                                         return res;
1723                                 } else if (res & RES_REPEAT) {
1724                                         int maxretries = res & 0xffff;
1725                                         if ((res & RES_RESTART) == RES_RESTART) {
1726                                                 retries = 0;
1727                                         } else {
1728                                                 retries++;
1729                                         }
1730                                         if (!maxretries) {
1731                                                 maxretries = 3;
1732                                         }
1733                                         if ((maxretries > 0) && (retries >= maxretries)) {
1734                                                 ast_debug(1, "Max retries %d exceeded\n", maxretries);
1735                                                 return -2;
1736                                         } else {
1737                                                 if (option_exists(menu, "g") > -1) {
1738                                                         strcpy(exten, "g");
1739                                                 } else if (option_exists(menu, "s") > -1) {
1740                                                         strcpy(exten, "s");
1741                                                 }
1742                                         }
1743                                         pos = 0;
1744                                         continue;
1745                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1746                                         ast_debug(1, "Got start of extension, %c\n", res);
1747                                         exten[1] = '\0';
1748                                         exten[0] = res;
1749                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
1750                                                 break;
1751                                         }
1752                                         if (option_exists(menu, exten) < 0) {
1753                                                 if (option_exists(menu, "i")) {
1754                                                         ast_debug(1, "Invalid extension entered, going to 'i'!\n");
1755                                                         strcpy(exten, "i");
1756                                                         pos = 0;
1757                                                         continue;
1758                                                 } else {
1759                                                         ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
1760                                                         res = -2;
1761                                                         break;
1762                                                 }
1763                                         } else {
1764                                                 ast_debug(1, "New existing extension: %s\n", exten);
1765                                                 pos = 0;
1766                                                 continue;
1767                                         }
1768                                 }
1769                         }
1770                         pos++;
1771                 }
1772                 ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
1773                 pos = 0;
1774                 if (!strcasecmp(exten, "s")) {
1775                         strcpy(exten, "g");
1776                 } else {
1777                         break;
1778                 }
1779         }
1780         return res;
1781 }
1782
1783 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1784 {
1785         int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1786         /* Hide internal coding */
1787         return res > 0 ? 0 : res;
1788 }
1789
1790 char *ast_read_textfile(const char *filename)
1791 {
1792         int fd, count = 0, res;
1793         char *output = NULL;
1794         struct stat filesize;
1795
1796         if (stat(filename, &filesize) == -1) {
1797                 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
1798                 return NULL;
1799         }
1800
1801         count = filesize.st_size + 1;
1802
1803         if ((fd = open(filename, O_RDONLY)) < 0) {
1804                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1805                 return NULL;
1806         }
1807
1808         if ((output = ast_malloc(count))) {
1809                 res = read(fd, output, count - 1);
1810                 if (res == count - 1) {
1811                         output[res] = '\0';
1812                 } else {
1813                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
1814                         ast_free(output);
1815                         output = NULL;
1816                 }
1817         }
1818
1819         close(fd);
1820
1821         return output;
1822 }
1823
1824 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
1825 {
1826         char *s, *arg;
1827         int curarg, res = 0;
1828         unsigned int argloc;
1829         struct ast_flags *flags = _flags;
1830         struct ast_flags64 *flags64 = _flags;
1831
1832         if (flaglen == 32) {
1833                 ast_clear_flag(flags, AST_FLAGS_ALL);
1834         } else {
1835                 flags64->flags = 0;
1836         }
1837
1838         if (!optstr) {
1839                 return 0;
1840         }
1841
1842         s = optstr;
1843         while (*s) {
1844                 curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
1845                 argloc = options[curarg].arg_index;
1846                 if (*s == '(') {
1847                         int paren = 1, quote = 0;
1848                         int parsequotes = (s[1] == '"') ? 1 : 0;
1849
1850                         /* Has argument */
1851                         arg = ++s;
1852                         for (; *s; s++) {
1853                                 if (*s == '(' && !quote) {
1854                                         paren++;
1855                                 } else if (*s == ')' && !quote) {
1856                                         /* Count parentheses, unless they're within quotes (or backslashed, below) */
1857                                         paren--;
1858                                 } else if (*s == '"' && parsequotes) {
1859                                         /* Leave embedded quotes alone, unless they are the first character */
1860                                         quote = quote ? 0 : 1;
1861                                         ast_copy_string(s, s + 1, INT_MAX);
1862                                         s--;
1863                                 } else if (*s == '\\') {
1864                                         if (!quote) {
1865                                                 /* If a backslash is found outside of quotes, remove it */
1866                                                 ast_copy_string(s, s + 1, INT_MAX);
1867                                         } else if (quote && s[1] == '"') {
1868                                                 /* Backslash for a quote character within quotes, remove the backslash */
1869                                                 ast_copy_string(s, s + 1, INT_MAX);
1870                                         } else {
1871                                                 /* Backslash within quotes, keep both characters */
1872                                                 s++;
1873                                         }
1874                                 }
1875
1876                                 if (paren == 0) {
1877                                         break;
1878                                 }
1879                         }
1880                         /* This will find the closing paren we found above, or none, if the string ended before we found one. */
1881                         if ((s = strchr(s, ')'))) {
1882                                 if (argloc) {
1883                                         args[argloc - 1] = arg;
1884                                 }
1885                                 *s++ = '\0';
1886                         } else {
1887                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1888                                 res = -1;
1889                                 break;
1890                         }
1891                 } else if (argloc) {
1892                         args[argloc - 1] = "";
1893                 }
1894                 if (flaglen == 32) {
1895                         ast_set_flag(flags, options[curarg].flag);
1896                 } else {
1897                         ast_set_flag64(flags64, options[curarg].flag);
1898                 }
1899         }
1900
1901         return res;
1902 }
1903
1904 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1905 {
1906         return parse_options(options, flags, args, optstr, 32);
1907 }
1908
1909 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
1910 {
1911         return parse_options(options, flags, args, optstr, 64);
1912 }
1913
1914 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
1915 {
1916         unsigned int i, found = 0;
1917         for (i = 32; i < 128 && found < len; i++) {
1918                 if (ast_test_flag64(flags, options[i].flag)) {
1919                         buf[found++] = i;
1920                 }
1921         }
1922         buf[found] = '\0';
1923 }
1924
1925 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
1926 {
1927         int i;
1928         *consumed = 1;
1929         *result = 0;
1930         if (ast_strlen_zero(stream)) {
1931                 *consumed = 0;
1932                 return -1;
1933         }
1934
1935         if (*stream == '\\') {
1936                 *consumed = 2;
1937                 switch (*(stream + 1)) {
1938                 case 'n':
1939                         *result = '\n';
1940                         break;
1941                 case 'r':
1942                         *result = '\r';
1943                         break;
1944                 case 't':
1945                         *result = '\t';
1946                         break;
1947                 case 'x':
1948                         /* Hexadecimal */
1949                         if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
1950                                 *consumed = 3;
1951                                 if (*(stream + 2) <= '9') {
1952                                         *result = *(stream + 2) - '0';
1953                                 } else if (*(stream + 2) <= 'F') {
1954                                         *result = *(stream + 2) - 'A' + 10;
1955                                 } else {
1956                                         *result = *(stream + 2) - 'a' + 10;
1957                                 }
1958                         } else {
1959                                 ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
1960                                 return -1;
1961                         }
1962
1963                         if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
1964                                 *consumed = 4;
1965                                 *result <<= 4;
1966                                 if (*(stream + 3) <= '9') {
1967                                         *result += *(stream + 3) - '0';
1968                                 } else if (*(stream + 3) <= 'F') {
1969                                         *result += *(stream + 3) - 'A' + 10;
1970                                 } else {
1971                                         *result += *(stream + 3) - 'a' + 10;
1972                                 }
1973                         }
1974                         break;
1975                 case '0':
1976                         /* Octal */
1977                         *consumed = 2;
1978                         for (i = 2; ; i++) {
1979                                 if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
1980                                         (*consumed)++;
1981                                         ast_debug(5, "result was %d, ", *result);
1982                                         *result <<= 3;
1983                                         *result += *(stream + i) - '0';
1984                                         ast_debug(5, "is now %d\n", *result);
1985                                 } else {
1986                                         break;
1987                                 }
1988                         }
1989                         break;
1990                 default:
1991                         *result = *(stream + 1);
1992                 }
1993         } else {
1994                 *result = *stream;
1995                 *consumed = 1;
1996         }
1997         return 0;
1998 }
1999
2000 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
2001 {
2002         char *cur = result;
2003         size_t consumed;
2004
2005         while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
2006                 cur++;
2007                 stream += consumed;
2008         }
2009         *cur = '\0';
2010         return result;
2011 }
2012
2013 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
2014 {
2015         char next, *buf;
2016         size_t offset = 0;
2017         size_t consumed;
2018
2019         if (strchr(stream, '\\')) {
2020                 while (!ast_get_encoded_char(stream, &next, &consumed)) {
2021                         if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
2022                                 ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
2023                         }
2024                         if (offset + 2 > ast_str_size(*str)) {
2025                                 break;
2026                         }
2027                         buf = ast_str_buffer(*str);
2028                         buf[offset++] = next;
2029                         stream += consumed;
2030                 }
2031                 buf = ast_str_buffer(*str);
2032                 buf[offset++] = '\0';
2033                 ast_str_update(*str);
2034         } else {
2035                 ast_str_set(str, maxlen, "%s", stream);
2036         }
2037         return 0;
2038 }
2039
2040 void ast_close_fds_above_n(int n)
2041 {
2042         closefrom(n + 1);
2043 }
2044
2045 int ast_safe_fork(int stop_reaper)
2046 {
2047         sigset_t signal_set, old_set;
2048         int pid;
2049
2050         /* Don't let the default signal handler for children reap our status */
2051         if (stop_reaper) {
2052                 ast_replace_sigchld();
2053         }
2054
2055         sigfillset(&signal_set);
2056         pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
2057
2058         pid = fork();
2059
2060         if (pid != 0) {
2061                 /* Fork failed or parent */
2062                 pthread_sigmask(SIG_SETMASK, &old_set, NULL);
2063                 return pid;
2064         } else {
2065                 /* Child */
2066 #ifdef HAVE_CAP
2067                 cap_t cap = cap_from_text("cap_net_admin-eip");
2068
2069                 if (cap_set_proc(cap)) {
2070                         ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
2071                 }
2072                 cap_free(cap);
2073 #endif
2074
2075                 /* Before we unblock our signals, return our trapped signals back to the defaults */
2076                 signal(SIGHUP, SIG_DFL);
2077                 signal(SIGCHLD, SIG_DFL);
2078                 signal(SIGINT, SIG_DFL);
2079                 signal(SIGURG, SIG_DFL);
2080                 signal(SIGTERM, SIG_DFL);
2081                 signal(SIGPIPE, SIG_DFL);
2082                 signal(SIGXFSZ, SIG_DFL);
2083
2084                 /* unblock important signal handlers */
2085                 if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
2086                         ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
2087                         _exit(1);
2088                 }
2089
2090                 return pid;
2091         }
2092 }
2093
2094 void ast_safe_fork_cleanup(void)
2095 {
2096         ast_unreplace_sigchld();
2097 }
2098
2099 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
2100 {
2101         int res;
2102         char u[10];
2103 #ifdef HAVE_LONG_DOUBLE_WIDER
2104         long double amount;
2105         #define FMT "%30Lf%9s"
2106 #else
2107         double amount;
2108         #define FMT "%30lf%9s"
2109 #endif
2110         if (!timestr) {
2111                 return -1;
2112         }
2113
2114         if ((res = sscanf(timestr, FMT, &amount, u)) == 0) {
2115 #undef FMT
2116                 return -1;
2117         } else if (res == 2) {
2118                 switch (u[0]) {
2119                 case 'h':
2120                 case 'H':
2121                         unit = TIMELEN_HOURS;
2122                         break;
2123                 case 's':
2124                 case 'S':
2125                         unit = TIMELEN_SECONDS;
2126                         break;
2127                 case 'm':
2128                 case 'M':
2129                         if (toupper(u[1]) == 'S') {
2130                                 unit = TIMELEN_MILLISECONDS;
2131                         } else if (u[1] == '\0') {
2132                                 unit = TIMELEN_MINUTES;
2133                         }
2134                         break;
2135                 }
2136         }
2137
2138         switch (unit) {
2139         case TIMELEN_HOURS:
2140                 amount *= 60;
2141                 /* fall-through */
2142         case TIMELEN_MINUTES:
2143                 amount *= 60;
2144                 /* fall-through */
2145         case TIMELEN_SECONDS:
2146                 amount *= 1000;
2147                 /* fall-through */
2148         case TIMELEN_MILLISECONDS:
2149                 ;
2150         }
2151         *result = amount > INT_MAX ? INT_MAX : (int) amount;
2152         return 0;
2153 }
2154