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