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