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