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