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