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