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