Add the ability to specify multiple prompts to the Read() dialplan application,
[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 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/time.h>
34 #include <signal.h>
35 #include <errno.h>
36 #include <unistd.h>
37 #include <dirent.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <regex.h>
41
42 #include "asterisk/channel.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/file.h"
45 #include "asterisk/app.h"
46 #include "asterisk/dsp.h"
47 #include "asterisk/logger.h"
48 #include "asterisk/options.h"
49 #include "asterisk/utils.h"
50 #include "asterisk/lock.h"
51 #include "asterisk/indications.h"
52
53 #define MAX_OTHER_FORMATS 10
54
55
56 /* !
57 This function presents a dialtone and reads an extension into 'collect' 
58 which must be a pointer to a **pre-initialized** array of char having a 
59 size of 'size' suitable for writing to.  It will collect no more than the smaller 
60 of 'maxlen' or 'size' minus the original strlen() of collect digits.
61 \return 0 if extension does not exist, 1 if extension exists
62 */
63 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout) 
64 {
65         struct tone_zone_sound *ts;
66         int res=0, x=0;
67
68         if (maxlen > size)
69                 maxlen = size;
70         
71         if (!timeout && chan->pbx)
72                 timeout = chan->pbx->dtimeout;
73         else if (!timeout)
74                 timeout = 5;
75         
76         ts = ast_get_indication_tone(chan->zone,"dial");
77         if (ts && ts->data[0])
78                 res = ast_playtones_start(chan, 0, ts->data, 0);
79         else 
80                 ast_log(LOG_NOTICE,"Huh....? no dial for indications?\n");
81         
82         for (x = strlen(collect); x < maxlen; ) {
83                 res = ast_waitfordigit(chan, timeout);
84                 if (!ast_ignore_pattern(context, collect))
85                         ast_playtones_stop(chan);
86                 if (res < 1)
87                         break;
88                 collect[x++] = res;
89                 if (!ast_matchmore_extension(chan, context, collect, 1, chan->cid.cid_num)) {
90                         if (collect[x-1] == '#') {
91                                 /* Not a valid extension, ending in #, assume the # was to finish dialing */
92                                 collect[x-1] = '\0';
93                         }
94                         break;
95                 }
96         }
97         if (res >= 0)
98                 res = ast_exists_extension(chan, context, collect, 1, chan->cid.cid_num) ? 1 : 0;
99         return res;
100 }
101
102 /*! \param c The channel to read from
103  *  \param prompt The file to stream to the channel
104  *  \param s The string to read in to.  Must be at least the size of your length
105  *  \param maxlen How many digits to read (maximum)
106  *  \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for 
107  *      "ludicrous time" (essentially never times out) */
108 int ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
109 {
110         int res = 0, to, fto;
111         char *front, *filename;
112
113         /* XXX Merge with full version? XXX */
114         
115         if (maxlen)
116                 s[0] = '\0';
117
118         if (ast_strlen_zero(prompt))
119                 return -1;
120
121         filename = ast_strdupa(prompt);
122         while ((front = strsep(&filename, "&"))) {
123                 res = ast_streamfile(c, front, c->language);
124                 if (res)
125                         continue;
126                 if (ast_strlen_zero(filename)) {
127                         /* set timeouts for the last prompt */
128                         fto = c->pbx ? c->pbx->rtimeout * 1000 : 6000;
129                         to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
130
131                         if (timeout > 0) 
132                                 fto = to = timeout;
133                         if (timeout < 0) 
134                                 fto = to = 1000000000;
135                 } else {
136                         /* there is more than one prompt, so
137                            get rid of the long timeout between 
138                            prompts, and make it 50ms */
139                         fto = 50;
140                         to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
141                 }
142                 res = ast_readstring(c, s, maxlen, to, fto, "#");
143                 if (!ast_strlen_zero(s))
144                         return res;
145         }
146         
147         return res;
148 }
149
150
151 int ast_app_getdata_full(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
152 {
153         int res, to, fto;
154         if (prompt) {
155                 res = ast_streamfile(c, prompt, c->language);
156                 if (res < 0)
157                         return res;
158         }
159         fto = 6000;
160         to = 2000;
161         if (timeout > 0) 
162                 fto = to = timeout;
163         if (timeout < 0) 
164                 fto = to = 1000000000;
165         res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
166         return res;
167 }
168
169 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
170 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
171 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
172
173 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
174                               int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
175                               int (*messagecount_func)(const char *context, const char *mailbox, const char *folder))
176 {
177         ast_has_voicemail_func = has_voicemail_func;
178         ast_inboxcount_func = inboxcount_func;
179         ast_messagecount_func = messagecount_func;
180 }
181
182 void ast_uninstall_vm_functions(void)
183 {
184         ast_has_voicemail_func = NULL;
185         ast_inboxcount_func = NULL;
186         ast_messagecount_func = NULL;
187 }
188
189 int ast_app_has_voicemail(const char *mailbox, const char *folder)
190 {
191         static int warned = 0;
192         if (ast_has_voicemail_func)
193                 return ast_has_voicemail_func(mailbox, folder);
194
195         if ((option_verbose > 2) && !warned) {
196                 ast_verbose(VERBOSE_PREFIX_3 "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
197                 warned++;
198         }
199         return 0;
200 }
201
202
203 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
204 {
205         static int warned = 0;
206         if (newmsgs)
207                 *newmsgs = 0;
208         if (oldmsgs)
209                 *oldmsgs = 0;
210         if (ast_inboxcount_func)
211                 return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
212
213         if (!warned && (option_verbose > 2)) {
214                 warned++;
215                 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
216         }
217
218         return 0;
219 }
220
221 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
222 {
223         static int warned = 0;
224         if (ast_messagecount_func)
225                 return ast_messagecount_func(context, mailbox, folder);
226
227         if (!warned && (option_verbose > 2)) {
228                 warned++;
229                 ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
230         }
231
232         return 0;
233 }
234
235 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between) 
236 {
237         const char *ptr;
238         int res = 0;
239
240         if (!between)
241                 between = 100;
242
243         if (peer)
244                 res = ast_autoservice_start(peer);
245
246         if (!res)
247                 res = ast_waitfor(chan, 100);
248
249         /* ast_waitfor will return the number of remaining ms on success */
250         if (res < 0)
251                 return res;
252
253         for (ptr = digits; *ptr; ptr++) {
254                 if (*ptr == 'w') {
255                         /* 'w' -- wait half a second */
256                         if ((res = ast_safe_sleep(chan, 500)))
257                                 break;
258                 } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
259                         /* Character represents valid DTMF */
260                         if (*ptr == 'f' || *ptr == 'F') {
261                                 /* ignore return values if not supported by channel */
262                                 ast_indicate(chan, AST_CONTROL_FLASH);
263                         } else
264                                 ast_senddigit(chan, *ptr);
265                         /* pause between digits */
266                         if ((res = ast_safe_sleep(chan, between)))
267                                 break;
268                 } else
269                         ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n",*ptr);
270         }
271
272         if (peer) {
273                 /* Stop autoservice on the peer channel, but don't overwrite any error condition 
274                    that has occurred previously while acting on the primary channel */
275                 if (ast_autoservice_stop(peer) && !res)
276                         res = -1;
277         }
278
279         return res;
280 }
281
282 struct linear_state {
283         int fd;
284         int autoclose;
285         int allowoverride;
286         int origwfmt;
287 };
288
289 static void linear_release(struct ast_channel *chan, void *params)
290 {
291         struct linear_state *ls = params;
292         if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
293                 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
294         }
295         if (ls->autoclose)
296                 close(ls->fd);
297         free(params);
298 }
299
300 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
301 {
302         struct ast_frame f;
303         short buf[2048 + AST_FRIENDLY_OFFSET / 2];
304         struct linear_state *ls = data;
305         int res;
306         len = samples * 2;
307         if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
308                 ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" ,len);
309                 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
310         }
311         memset(&f, 0, sizeof(f));
312         res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
313         if (res > 0) {
314                 f.frametype = AST_FRAME_VOICE;
315                 f.subclass = AST_FORMAT_SLINEAR;
316                 f.data = buf + AST_FRIENDLY_OFFSET/2;
317                 f.datalen = res;
318                 f.samples = res / 2;
319                 f.offset = AST_FRIENDLY_OFFSET;
320                 ast_write(chan, &f);
321                 if (res == len)
322                         return 0;
323         }
324         return -1;
325 }
326
327 static void *linear_alloc(struct ast_channel *chan, void *params)
328 {
329         struct linear_state *ls;
330         /* In this case, params is already malloc'd */
331         if (params) {
332                 ls = params;
333                 if (ls->allowoverride)
334                         ast_set_flag(chan, AST_FLAG_WRITE_INT);
335                 else
336                         ast_clear_flag(chan, AST_FLAG_WRITE_INT);
337                 ls->origwfmt = chan->writeformat;
338                 if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
339                         ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
340                         free(ls);
341                         ls = params = NULL;
342                 }
343         }
344         return params;
345 }
346
347 static struct ast_generator linearstream = 
348 {
349         alloc: linear_alloc,
350         release: linear_release,
351         generate: linear_generator,
352 };
353
354 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
355 {
356         struct linear_state *lin;
357         char tmpf[256];
358         int res = -1;
359         int autoclose = 0;
360         if (fd < 0) {
361                 if (ast_strlen_zero(filename))
362                         return -1;
363                 autoclose = 1;
364                 if (filename[0] == '/') 
365                         ast_copy_string(tmpf, filename, sizeof(tmpf));
366                 else
367                         snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
368                 fd = open(tmpf, O_RDONLY);
369                 if (fd < 0){
370                         ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
371                         return -1;
372                 }
373         }
374         if ((lin = ast_calloc(1, sizeof(*lin)))) {
375                 lin->fd = fd;
376                 lin->allowoverride = allowoverride;
377                 lin->autoclose = autoclose;
378                 res = ast_activate_generator(chan, &linearstream, lin);
379         }
380         return res;
381 }
382
383 int ast_control_streamfile(struct ast_channel *chan, const char *file,
384                            const char *fwd, const char *rev,
385                            const char *stop, const char *pause,
386                            const char *restart, int skipms) 
387 {
388         char *breaks = NULL;
389         char *end = NULL;
390         int blen = 2;
391         int res;
392         long pause_restart_point = 0;
393
394         if (stop)
395                 blen += strlen(stop);
396         if (pause)
397                 blen += strlen(pause);
398         if (restart)
399                 blen += strlen(restart);
400
401         if (blen > 2) {
402                 breaks = alloca(blen + 1);
403                 breaks[0] = '\0';
404                 if (stop)
405                         strcat(breaks, stop);
406                 if (pause)
407                         strcat(breaks, pause);
408                 if (restart)
409                         strcat(breaks, restart);
410         }
411         if (chan->_state != AST_STATE_UP)
412                 res = ast_answer(chan);
413
414         if (file) {
415                 if ((end = strchr(file,':'))) {
416                         if (!strcasecmp(end, ":end")) {
417                                 *end = '\0';
418                                 end++;
419                         }
420                 }
421         }
422
423         for (;;) {
424                 ast_stopstream(chan);
425                 res = ast_streamfile(chan, file, chan->language);
426                 if (!res) {
427                         if (pause_restart_point) {
428                                 ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
429                                 pause_restart_point = 0;
430                         }
431                         else if (end) {
432                                 ast_seekstream(chan->stream, 0, SEEK_END);
433                                 end = NULL;
434                         };
435                         res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
436                 }
437
438                 if (res < 1)
439                         break;
440
441                 /* We go at next loop if we got the restart char */
442                 if (restart && strchr(restart, res)) {
443                         if (option_debug)
444                                 ast_log(LOG_DEBUG, "we'll restart the stream here at next loop\n");
445                         pause_restart_point = 0;
446                         continue;
447                 }
448
449                 if (pause && strchr(pause, res)) {
450                         pause_restart_point = ast_tellstream(chan->stream);
451                         for (;;) {
452                                 ast_stopstream(chan);
453                                 res = ast_waitfordigit(chan, 1000);
454                                 if (!res)
455                                         continue;
456                                 else if (res == -1 || strchr(pause, res) || (stop && strchr(stop, res)))
457                                         break;
458                         }
459                         if (res == *pause) {
460                                 res = 0;
461                                 continue;
462                         }
463                 }
464
465                 if (res == -1)
466                         break;
467
468                 /* if we get one of our stop chars, return it to the calling function */
469                 if (stop && strchr(stop, res))
470                         break;
471         }
472
473         ast_stopstream(chan);
474
475         return res;
476 }
477
478 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
479 {
480         int d;
481         d = ast_streamfile(chan, fn, chan->language);
482         if (d)
483                 return d;
484         d = ast_waitstream(chan, AST_DIGIT_ANY);
485         ast_stopstream(chan);
486         return d;
487 }
488
489 static int global_silence_threshold = 128;
490 static int global_maxsilence = 0;
491
492 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
493  * @param chan Channel to playback to/record from.
494  * @param playfile Filename of sound to play before recording begins.
495  * @param recordfile Filename to record to.
496  * @param maxtime Maximum length of recording (in milliseconds).
497  * @param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
498  * @param duration Where to store actual length of the recorded message (in milliseconds).
499  * @param beep Whether to play a beep before starting to record.
500  * @param silencethreshold 
501  * @param maxsilence Length of silence that will end a recording (in milliseconds).
502  * @param path Optional filesystem path to unlock.
503  * @param prepend If true, prepend the recorded audio to an existing file.
504  * @param acceptdtmf DTMF digits that will end the recording.
505  * @param canceldtmf DTMF digits that will cancel the recording.
506  */
507
508 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)
509 {
510         int d = 0;
511         char *fmts;
512         char comment[256];
513         int x, fmtcnt = 1, res = -1, outmsg = 0;
514         struct ast_filestream *others[MAX_OTHER_FORMATS];
515         char *sfmt[MAX_OTHER_FORMATS];
516         char *stringp = NULL;
517         time_t start, end;
518         struct ast_dsp *sildet = NULL;   /* silence detector dsp */
519         int totalsilence = 0;
520         int rfmt = 0;
521         struct ast_silence_generator *silgen = NULL;
522         char prependfile[80];
523
524         if (silencethreshold < 0)
525                 silencethreshold = global_silence_threshold;
526
527         if (maxsilence < 0)
528                 maxsilence = global_maxsilence;
529
530         /* barf if no pointer passed to store duration in */
531         if (duration == NULL) {
532                 ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
533                 return -1;
534         }
535
536         if (option_debug)
537                 ast_log(LOG_DEBUG,"play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
538         snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
539
540         if (playfile || beep) {
541                 if (!beep)
542                         d = ast_play_and_wait(chan, playfile);
543                 if (d > -1)
544                         d = ast_stream_and_wait(chan, "beep", chan->language, "");
545                 if (d < 0)
546                         return -1;
547         }
548
549         if (prepend) {
550                 ast_copy_string(prependfile, recordfile, sizeof(prependfile));  
551                 strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
552         }
553
554         fmts = ast_strdupa(fmt);
555
556         stringp = fmts;
557         strsep(&stringp, "|");
558         if (option_debug)
559                 ast_log(LOG_DEBUG, "Recording Formats: sfmts=%s\n", fmts);
560         sfmt[0] = ast_strdupa(fmts);
561
562         while ((fmt = strsep(&stringp, "|"))) {
563                 if (fmtcnt > MAX_OTHER_FORMATS - 1) {
564                         ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app.c\n");
565                         break;
566                 }
567                 sfmt[fmtcnt++] = ast_strdupa(fmt);
568         }
569
570         end = start = time(NULL);  /* pre-initialize end to be same as start in case we never get into loop */
571         for (x = 0; x < fmtcnt; x++) {
572                 others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, 0700);
573                 if (option_verbose > 2)
574                         ast_verbose(VERBOSE_PREFIX_3 "x=%d, open writing:  %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
575
576                 if (!others[x])
577                         break;
578         }
579
580         if (path)
581                 ast_unlock_path(path);
582
583         if (maxsilence > 0) {
584                 sildet = ast_dsp_new(); /* Create the silence detector */
585                 if (!sildet) {
586                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
587                         return -1;
588                 }
589                 ast_dsp_set_threshold(sildet, silencethreshold);
590                 rfmt = chan->readformat;
591                 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
592                 if (res < 0) {
593                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
594                         ast_dsp_free(sildet);
595                         return -1;
596                 }
597         }
598
599         if (!prepend) {
600                 /* Request a video update */
601                 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
602
603                 if (ast_opt_transmit_silence)
604                         silgen = ast_channel_start_silence_generator(chan);
605         }
606
607         if (x == fmtcnt) {
608                 /* Loop forever, writing the packets we read to the writer(s), until
609                    we read a digit or get a hangup */
610                 struct ast_frame *f;
611                 for (;;) {
612                         res = ast_waitfor(chan, 2000);
613                         if (!res) {
614                                 if (option_debug)
615                                         ast_log(LOG_DEBUG, "One waitfor failed, trying another\n");
616                                 /* Try one more time in case of masq */
617                                 res = ast_waitfor(chan, 2000);
618                                 if (!res) {
619                                         ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
620                                         res = -1;
621                                 }
622                         }
623
624                         if (res < 0) {
625                                 f = NULL;
626                                 break;
627                         }
628                         f = ast_read(chan);
629                         if (!f)
630                                 break;
631                         if (f->frametype == AST_FRAME_VOICE) {
632                                 /* write each format */
633                                 for (x = 0; x < fmtcnt; x++) {
634                                         if (prepend && !others[x])
635                                                 break;
636                                         res = ast_writestream(others[x], f);
637                                 }
638
639                                 /* Silence Detection */
640                                 if (maxsilence > 0) {
641                                         int dspsilence = 0;
642                                         ast_dsp_silence(sildet, f, &dspsilence);
643                                         if (dspsilence)
644                                                 totalsilence = dspsilence;
645                                         else
646                                                 totalsilence = 0;
647
648                                         if (totalsilence > maxsilence) {
649                                                 /* Ended happily with silence */
650                                                 if (option_verbose > 2)
651                                                         ast_verbose( VERBOSE_PREFIX_3 "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
652                                                 res = 'S';
653                                                 outmsg = 2;
654                                                 break;
655                                         }
656                                 }
657                                 /* Exit on any error */
658                                 if (res) {
659                                         ast_log(LOG_WARNING, "Error writing frame\n");
660                                         break;
661                                 }
662                         } else if (f->frametype == AST_FRAME_VIDEO) {
663                                 /* Write only once */
664                                 ast_writestream(others[0], f);
665                         } else if (f->frametype == AST_FRAME_DTMF) {
666                                 if (prepend) {
667                                 /* stop recording with any digit */
668                                         if (option_verbose > 2) 
669                                                 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
670                                         res = 't';
671                                         outmsg = 2;
672                                         break;
673                                 }
674                                 if (strchr(acceptdtmf, f->subclass)) {
675                                         if (option_verbose > 2)
676                                                 ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
677                                         res = f->subclass;
678                                         outmsg = 2;
679                                         break;
680                                 }
681                                 if (strchr(canceldtmf, f->subclass)) {
682                                         if (option_verbose > 2)
683                                                 ast_verbose(VERBOSE_PREFIX_3 "User cancelled message by pressing %c\n", f->subclass);
684                                         res = f->subclass;
685                                         outmsg = 0;
686                                         break;
687                                 }
688                         }
689                         if (maxtime) {
690                                 end = time(NULL);
691                                 if (maxtime < (end - start)) {
692                                         if (option_verbose > 2)
693                                                 ast_verbose(VERBOSE_PREFIX_3 "Took too long, cutting it short...\n");
694                                         res = 't';
695                                         outmsg = 2;
696                                         break;
697                                 }
698                         }
699                         ast_frfree(f);
700                 }
701                 if (!f) {
702                         if (option_verbose > 2)
703                                 ast_verbose(VERBOSE_PREFIX_3 "User hung up\n");
704                         res = -1;
705                         outmsg = 1;
706                 } else {
707                         ast_frfree(f);
708                 }
709                 if (end == start)
710                         end = time(NULL);
711         } else {
712                 ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
713         }
714
715         if (!prepend) {
716                 if (silgen)
717                         ast_channel_stop_silence_generator(chan, silgen);
718         }
719         *duration = end - start;
720
721         if (!prepend) {
722                 for (x = 0; x < fmtcnt; x++) {
723                         if (!others[x])
724                                 break;
725                         if (res > 0)
726                                 ast_stream_rewind(others[x], totalsilence ? totalsilence - 200 : 200);
727                         ast_truncstream(others[x]);
728                         ast_closestream(others[x]);
729                 }
730         }
731
732         if (prepend && outmsg) {
733                 struct ast_filestream *realfiles[MAX_OTHER_FORMATS];
734                 struct ast_frame *fr;
735
736                 for (x = 0; x < fmtcnt; x++) {
737                         snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
738                         realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
739                         if (!others[x] || !realfiles[x])
740                                 break;
741                         ast_stream_rewind(others[x], totalsilence ? totalsilence - 200 : 200);
742                         ast_truncstream(others[x]);
743                         /* add the original file too */
744                         while ((fr = ast_readframe(realfiles[x]))) {
745                                 ast_writestream(others[x], fr);
746                                 ast_frfree(fr);
747                         }
748                         ast_closestream(others[x]);
749                         ast_closestream(realfiles[x]);
750                         ast_filerename(prependfile, recordfile, sfmt[x]);
751                         if (option_verbose > 3)
752                                 ast_verbose(VERBOSE_PREFIX_4 "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
753                         ast_filedelete(prependfile, sfmt[x]);
754                 }
755         }
756         if (rfmt && ast_set_read_format(chan, rfmt)) {
757                 ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
758         }
759         if (outmsg == 2) {
760                 ast_stream_and_wait(chan, "auth-thankyou", chan->language, "");
761         }
762         if (sildet)
763                 ast_dsp_free(sildet);
764         return res;
765 }
766
767 static char default_acceptdtmf[] = "#";
768 static char default_canceldtmf[] = "";
769
770 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)
771 {
772         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));
773 }
774
775 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)
776 {
777         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf);
778 }
779
780 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)
781 {
782         return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf);
783 }
784
785 /* Channel group core functions */
786
787 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
788 {
789         int res=0;
790         char tmp[256];
791         char *grp=NULL, *cat=NULL;
792
793         if (!ast_strlen_zero(data)) {
794                 ast_copy_string(tmp, data, sizeof(tmp));
795                 grp = tmp;
796                 cat = strchr(tmp, '@');
797                 if (cat) {
798                         *cat = '\0';
799                         cat++;
800                 }
801         }
802
803         if (!ast_strlen_zero(grp))
804                 ast_copy_string(group, grp, group_max);
805         else
806                 res = -1;
807
808         if (cat)
809                 snprintf(category, category_max, "%s_%s", GROUP_CATEGORY_PREFIX, cat);
810         else
811                 ast_copy_string(category, GROUP_CATEGORY_PREFIX, category_max);
812
813         return res;
814 }
815
816 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
817 {
818         int res=0;
819         char group[80] = "";
820         char category[80] = "";
821
822         if (!ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
823                 pbx_builtin_setvar_helper(chan, category, group);
824         } else
825                 res = -1;
826
827         return res;
828 }
829
830 int ast_app_group_get_count(const char *group, const char *category)
831 {
832         struct ast_channel *chan;
833         int count = 0;
834         const char *test;
835         char cat[80];
836         const char *s;
837
838         if (ast_strlen_zero(group))
839                 return 0;
840
841         s = S_OR(category, GROUP_CATEGORY_PREFIX);
842         ast_copy_string(cat, s, sizeof(cat));
843
844         chan = NULL;
845         while ((chan = ast_channel_walk_locked(chan)) != NULL) {
846                 test = pbx_builtin_getvar_helper(chan, cat);
847                 if (test && !strcasecmp(test, group))
848                         count++;
849                 ast_channel_unlock(chan);
850         }
851
852         return count;
853 }
854
855 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
856 {
857         regex_t regexbuf;
858         struct ast_channel *chan;
859         int count = 0;
860         const char *test;
861         char cat[80];
862         const char *s;
863
864         if (ast_strlen_zero(groupmatch))
865                 return 0;
866
867         /* if regex compilation fails, return zero matches */
868         if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
869                 return 0;
870
871         s = S_OR(category, GROUP_CATEGORY_PREFIX);
872         ast_copy_string(cat, s, sizeof(cat));
873
874         chan = NULL;
875         while ((chan = ast_channel_walk_locked(chan)) != NULL) {
876                 test = pbx_builtin_getvar_helper(chan, cat);
877                 if (test && !regexec(&regexbuf, test, 0, NULL, 0))
878                         count++;
879                 ast_channel_unlock(chan);
880         }
881
882         regfree(&regexbuf);
883
884         return count;
885 }
886
887 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
888 {
889         int argc;
890         char *scan;
891         int paren = 0, quote = 0;
892
893         if (!buf || !array || !arraylen)
894                 return 0;
895
896         memset(array, 0, arraylen * sizeof(*array));
897
898         scan = buf;
899
900         for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
901                 array[argc] = scan;
902                 for (; *scan; scan++) {
903                         if (*scan == '(')
904                                 paren++;
905                         else if (*scan == ')') {
906                                 if (paren)
907                                         paren--;
908                         } else if (*scan == '"' && delim != '"') {
909                                 quote = quote ? 0 : 1;
910                                 /* Remove quote character from argument */
911                                 memmove(scan, scan + 1, strlen(scan));
912                                 scan--;
913                         } else if (*scan == '\\') {
914                                 /* Literal character, don't parse */
915                                 memmove(scan, scan + 1, strlen(scan));
916                         } else if ((*scan == delim) && !paren && !quote) {
917                                 *scan++ = '\0';
918                                 break;
919                         }
920                 }
921         }
922
923         if (*scan)
924                 array[argc++] = scan;
925
926         return argc;
927 }
928
929 enum AST_LOCK_RESULT ast_lock_path(const char *path)
930 {
931         char *s;
932         char *fs;
933         int res;
934         int fd;
935         int lp = strlen(path);
936         time_t start;
937
938         if (!(s = alloca(lp + 10)) || !(fs = alloca(lp + 20))) {
939                 ast_log(LOG_WARNING, "Out of memory!\n");
940                 return AST_LOCK_FAILURE;
941         }
942
943         snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
944         fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
945         if (fd < 0) {
946                 ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
947                 return AST_LOCK_PATH_NOT_FOUND;
948         }
949         close(fd);
950
951         snprintf(s, strlen(path) + 9, "%s/.lock", path);
952         start = time(NULL);
953         while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
954                 usleep(1);
955
956         unlink(fs);
957
958         if (res) {
959                 ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
960                 return AST_LOCK_TIMEOUT;
961         } else {
962                 if (option_debug)
963                         ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
964                 return AST_LOCK_SUCCESS;
965         }
966 }
967
968 int ast_unlock_path(const char *path)
969 {
970         char *s;
971         int res;
972
973         if (!(s = alloca(strlen(path) + 10))) {
974                 ast_log(LOG_WARNING, "Out of memory!\n");
975                 return -1;
976         }
977
978         snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
979
980         if ((res = unlink(s)))
981                 ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
982         else {
983                 if (option_debug)
984                         ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
985         }
986
987         return res;
988 }
989
990 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
991 {
992         int silencethreshold = 128; 
993         int maxsilence=0;
994         int res = 0;
995         int cmd = 0;
996         int max_attempts = 3;
997         int attempts = 0;
998         int recorded = 0;
999         int message_exists = 0;
1000         /* Note that urgent and private are for flagging messages as such in the future */
1001
1002         /* barf if no pointer passed to store duration in */
1003         if (duration == NULL) {
1004                 ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
1005                 return -1;
1006         }
1007
1008         cmd = '3';       /* Want to start by recording */
1009
1010         while ((cmd >= 0) && (cmd != 't')) {
1011                 switch (cmd) {
1012                 case '1':
1013                         if (!message_exists) {
1014                                 /* In this case, 1 is to record a message */
1015                                 cmd = '3';
1016                                 break;
1017                         } else {
1018                                 ast_stream_and_wait(chan, "vm-msgsaved", chan->language, "");
1019                                 cmd = 't';
1020                                 return res;
1021                         }
1022                 case '2':
1023                         /* Review */
1024                         ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
1025                         cmd = ast_stream_and_wait(chan, recordfile, chan->language, AST_DIGIT_ANY);
1026                         break;
1027                 case '3':
1028                         message_exists = 0;
1029                         /* Record */
1030                         if (recorded == 1)
1031                                 ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
1032                         else    
1033                                 ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
1034                         recorded = 1;
1035                         cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
1036                         if (cmd == -1) {
1037                         /* User has hung up, no options to give */
1038                                 return cmd;
1039                         }
1040                         if (cmd == '0') {
1041                                 break;
1042                         } else if (cmd == '*') {
1043                                 break;
1044                         } 
1045                         else {
1046                                 /* If all is well, a message exists */
1047                                 message_exists = 1;
1048                                 cmd = 0;
1049                         }
1050                         break;
1051                 case '4':
1052                 case '5':
1053                 case '6':
1054                 case '7':
1055                 case '8':
1056                 case '9':
1057                 case '*':
1058                 case '#':
1059                         cmd = ast_play_and_wait(chan, "vm-sorry");
1060                         break;
1061                 default:
1062                         if (message_exists) {
1063                                 cmd = ast_play_and_wait(chan, "vm-review");
1064                         }
1065                         else {
1066                                 cmd = ast_play_and_wait(chan, "vm-torerecord");
1067                                 if (!cmd)
1068                                         cmd = ast_waitfordigit(chan, 600);
1069                         }
1070                         
1071                         if (!cmd)
1072                                 cmd = ast_waitfordigit(chan, 6000);
1073                         if (!cmd) {
1074                                 attempts++;
1075                         }
1076                         if (attempts > max_attempts) {
1077                                 cmd = 't';
1078                         }
1079                 }
1080         }
1081         if (cmd == 't')
1082                 cmd = 0;
1083         return cmd;
1084 }
1085
1086 #define RES_UPONE (1 << 16)
1087 #define RES_EXIT  (1 << 17)
1088 #define RES_REPEAT (1 << 18)
1089 #define RES_RESTART ((1 << 19) | RES_REPEAT)
1090
1091 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
1092
1093 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
1094 {
1095         int res;
1096         int (*ivr_func)(struct ast_channel *, void *);
1097         char *c;
1098         char *n;
1099         
1100         switch(option->action) {
1101         case AST_ACTION_UPONE:
1102                 return RES_UPONE;
1103         case AST_ACTION_EXIT:
1104                 return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
1105         case AST_ACTION_REPEAT:
1106                 return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
1107         case AST_ACTION_RESTART:
1108                 return RES_RESTART ;
1109         case AST_ACTION_NOOP:
1110                 return 0;
1111         case AST_ACTION_BACKGROUND:
1112                 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, AST_DIGIT_ANY);
1113                 if (res < 0) {
1114                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1115                         res = 0;
1116                 }
1117                 return res;
1118         case AST_ACTION_PLAYBACK:
1119                 res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, "");
1120                 if (res < 0) {
1121                         ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
1122                         res = 0;
1123                 }
1124                 return res;
1125         case AST_ACTION_MENU:
1126                 res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
1127                 /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
1128                 if (res == -2)
1129                         res = 0;
1130                 return res;
1131         case AST_ACTION_WAITOPTION:
1132                 res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
1133                 if (!res)
1134                         return 't';
1135                 return res;
1136         case AST_ACTION_CALLBACK:
1137                 ivr_func = option->adata;
1138                 res = ivr_func(chan, cbdata);
1139                 return res;
1140         case AST_ACTION_TRANSFER:
1141                 res = ast_parseable_goto(chan, option->adata);
1142                 return 0;
1143         case AST_ACTION_PLAYLIST:
1144         case AST_ACTION_BACKLIST:
1145                 res = 0;
1146                 c = ast_strdupa(option->adata);
1147                 while ((n = strsep(&c, ";"))) {
1148                         if ((res = ast_stream_and_wait(chan, n, chan->language,
1149                                         (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
1150                                 break;
1151                 }
1152                 ast_stopstream(chan);
1153                 return res;
1154         default:
1155                 ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
1156                 return 0;
1157         };
1158         return -1;
1159 }
1160
1161 static int option_exists(struct ast_ivr_menu *menu, char *option)
1162 {
1163         int x;
1164         for (x = 0; menu->options[x].option; x++)
1165                 if (!strcasecmp(menu->options[x].option, option))
1166                         return x;
1167         return -1;
1168 }
1169
1170 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
1171 {
1172         int x;
1173         for (x = 0; menu->options[x].option; x++)
1174                 if ((!strncasecmp(menu->options[x].option, option, strlen(option))) && 
1175                                 (menu->options[x].option[strlen(option)]))
1176                         return x;
1177         return -1;
1178 }
1179
1180 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
1181 {
1182         int res=0;
1183         int ms;
1184         while (option_matchmore(menu, exten)) {
1185                 ms = chan->pbx ? chan->pbx->dtimeout : 5000;
1186                 if (strlen(exten) >= maxexten - 1) 
1187                         break;
1188                 res = ast_waitfordigit(chan, ms);
1189                 if (res < 1)
1190                         break;
1191                 exten[strlen(exten) + 1] = '\0';
1192                 exten[strlen(exten)] = res;
1193         }
1194         return res > 0 ? 0 : res;
1195 }
1196
1197 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1198 {
1199         /* Execute an IVR menu structure */
1200         int res=0;
1201         int pos = 0;
1202         int retries = 0;
1203         char exten[AST_MAX_EXTENSION] = "s";
1204         if (option_exists(menu, "s") < 0) {
1205                 strcpy(exten, "g");
1206                 if (option_exists(menu, "g") < 0) {
1207                         ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
1208                         return -1;
1209                 }
1210         }
1211         while(!res) {
1212                 while(menu->options[pos].option) {
1213                         if (!strcasecmp(menu->options[pos].option, exten)) {
1214                                 res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
1215                                 if (option_debug)
1216                                         ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
1217                                 if (res < 0)
1218                                         break;
1219                                 else if (res & RES_UPONE)
1220                                         return 0;
1221                                 else if (res & RES_EXIT)
1222                                         return res;
1223                                 else if (res & RES_REPEAT) {
1224                                         int maxretries = res & 0xffff;
1225                                         if ((res & RES_RESTART) == RES_RESTART) {
1226                                                 retries = 0;
1227                                         } else
1228                                                 retries++;
1229                                         if (!maxretries)
1230                                                 maxretries = 3;
1231                                         if ((maxretries > 0) && (retries >= maxretries)) {
1232                                                 if (option_debug)
1233                                                         ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
1234                                                 return -2;
1235                                         } else {
1236                                                 if (option_exists(menu, "g") > -1) 
1237                                                         strcpy(exten, "g");
1238                                                 else if (option_exists(menu, "s") > -1)
1239                                                         strcpy(exten, "s");
1240                                         }
1241                                         pos = 0;
1242                                         continue;
1243                                 } else if (res && strchr(AST_DIGIT_ANY, res)) {
1244                                         if (option_debug)
1245                                                 ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
1246                                         exten[1] = '\0';
1247                                         exten[0] = res;
1248                                         if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
1249                                                 break;
1250                                         if (option_exists(menu, exten) < 0) {
1251                                                 if (option_exists(menu, "i")) {
1252                                                         if (option_debug)
1253                                                                 ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
1254                                                         strcpy(exten, "i");
1255                                                         pos = 0;
1256                                                         continue;
1257                                                 } else {
1258                                                         if (option_debug)
1259                                                                 ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
1260                                                         res = -2;
1261                                                         break;
1262                                                 }
1263                                         } else {
1264                                                 if (option_debug)
1265                                                         ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
1266                                                 pos = 0;
1267                                                 continue;
1268                                         }
1269                                 }
1270                         }
1271                         pos++;
1272                 }
1273                 if (option_debug)
1274                         ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
1275                 pos = 0;
1276                 if (!strcasecmp(exten, "s"))
1277                         strcpy(exten, "g");
1278                 else
1279                         break;
1280         }
1281         return res;
1282 }
1283
1284 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
1285 {
1286         int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
1287         /* Hide internal coding */
1288         return res > 0 ? 0 : res;
1289 }
1290         
1291 char *ast_read_textfile(const char *filename)
1292 {
1293         int fd;
1294         char *output = NULL;
1295         struct stat filesize;
1296         int count = 0;
1297         int res;
1298         if (stat(filename, &filesize) == -1) {
1299                 ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
1300                 return NULL;
1301         }
1302         count = filesize.st_size + 1;
1303         fd = open(filename, O_RDONLY);
1304         if (fd < 0) {
1305                 ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
1306                 return NULL;
1307         }
1308         if ((output = ast_malloc(count))) {
1309                 res = read(fd, output, count - 1);
1310                 if (res == count - 1) {
1311                         output[res] = '\0';
1312                 } else {
1313                         ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
1314                         free(output);
1315                         output = NULL;
1316                 }
1317         }
1318         close(fd);
1319         return output;
1320 }
1321
1322 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
1323 {
1324         char *s;
1325         int curarg;
1326         unsigned int argloc;
1327         char *arg;
1328         int res = 0;
1329
1330         ast_clear_flag(flags, AST_FLAGS_ALL);
1331
1332         if (!optstr)
1333                 return 0;
1334
1335         s = optstr;
1336         while (*s) {
1337                 curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
1338                 ast_set_flag(flags, options[curarg].flag);
1339                 argloc = options[curarg].arg_index;
1340                 if (*s == '(') {
1341                         /* Has argument */
1342                         arg = ++s;
1343                         if ((s = strchr(s, ')'))) {
1344                                 if (argloc)
1345                                         args[argloc - 1] = arg;
1346                                 *s++ = '\0';
1347                         } else {
1348                                 ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
1349                                 res = -1;
1350                                 break;
1351                         }
1352                 } else if (argloc) {
1353                         args[argloc - 1] = NULL;
1354                 }
1355         }
1356
1357         return res;
1358 }
1359