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