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