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