BSD portability enhancements (bug #234)
[asterisk/asterisk.git] / apps / app_agi.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Asterisk Gateway Interface
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <sys/types.h>
15 #include <asterisk/file.h>
16 #include <asterisk/logger.h>
17 #include <asterisk/channel.h>
18 #include <asterisk/pbx.h>
19 #include <asterisk/module.h>
20 #include <asterisk/astdb.h>
21 #include <math.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <signal.h>
27 #include <sys/time.h>
28 #include <stdio.h>
29 #include <fcntl.h>
30 #include <errno.h>
31 #include <asterisk/cli.h>
32 #include <asterisk/logger.h>
33 #include <asterisk/options.h>
34 #include <asterisk/image.h>
35 #include <asterisk/say.h>
36 #include <asterisk/app.h>
37 #include <asterisk/dsp.h>
38 #include <asterisk/musiconhold.h>
39 #include "../asterisk.h"
40 #include "../astconf.h"
41
42 #include <pthread.h>
43
44 #define MAX_ARGS 128
45
46 /* Recycle some stuff from the CLI interface */
47 #define fdprintf ast_cli
48
49 typedef struct agi_state {
50         int fd;         /* FD for general output */
51         int audio;      /* FD for audio output */
52         int ctrl;       /* FD for input control */
53 } AGI;
54
55 typedef struct agi_command {
56         /* Null terminated list of the words of the command */
57         char *cmda[AST_MAX_CMD_LEN];
58         /* Handler for the command (channel, AGI state, # of arguments, argument list). 
59             Returns RESULT_SHOWUSAGE for improper arguments */
60         int (*handler)(struct ast_channel *chan, AGI *agi, int argc, char *argv[]);
61         /* Summary of the command (< 60 characters) */
62         char *summary;
63         /* Detailed usage information */
64         char *usage;
65 } agi_command;
66
67 static char *tdesc = "Asterisk Gateway Interface (AGI)";
68
69 static char *app = "AGI";
70
71 static char *eapp = "EAGI";
72
73 static char *synopsis = "Executes an AGI compliant application";
74
75 static char *descrip =
76 "  [E]AGI(command|args): Executes an Asterisk Gateway Interface compliant\n"
77 "program on a channel.   AGI allows Asterisk to launch external programs\n"
78 "written in any language to control a telephony channel, play audio,\n"
79 "read DTMF digits, etc. by communicating with the AGI protocol on stdin\n"
80 "and stdout.  Returns -1 on hangup or if application requested hangup, or\n"
81 "0 on non-hangup exit.  Using 'EAGI' provides enhanced AGI, with audio\n"
82 "available out of band on file descriptor 3\n";
83
84 STANDARD_LOCAL_USER;
85
86 LOCAL_USER_DECL;
87
88
89 #define TONE_BLOCK_SIZE 200
90
91 static int launch_script(char *script, char *args, int *fds, int *efd, int *opid)
92 {
93         char tmp[256];
94         int pid;
95         int toast[2];
96         int fromast[2];
97         int audio[2];
98         int x;
99         int res;
100         if (script[0] != '/') {
101                 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_AGI_DIR, script);
102                 script = tmp;
103         }
104         if (pipe(toast)) {
105                 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
106                 return -1;
107         }
108         if (pipe(fromast)) {
109                 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
110                 close(toast[0]);
111                 close(toast[1]);
112                 return -1;
113         }
114         if (efd) {
115                 if (pipe(audio)) {
116                         ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
117                         close(fromast[0]);
118                         close(fromast[1]);
119                         close(toast[0]);
120                         close(toast[1]);
121                         return -1;
122                 }
123                 res = fcntl(audio[1], F_GETFL);
124                 if (res > -1) 
125                         res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
126                 if (res < 0) {
127                         ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
128                         close(fromast[0]);
129                         close(fromast[1]);
130                         close(toast[0]);
131                         close(toast[1]);
132                         close(audio[0]);
133                         close(audio[1]);
134                         return -1;
135                 }
136         }
137         pid = fork();
138         if (pid < 0) {
139                 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
140                 return -1;
141         }
142         if (!pid) {
143                 /* Redirect stdin and out, provide enhanced audio channel if desired */
144                 dup2(fromast[0], STDIN_FILENO);
145                 dup2(toast[1], STDOUT_FILENO);
146                 if (efd) {
147                         dup2(audio[0], STDERR_FILENO + 1);
148                 } else {
149                         close(STDERR_FILENO + 1);
150                 }
151                 /* Close everything but stdin/out/error */
152                 for (x=STDERR_FILENO + 2;x<1024;x++) 
153                         close(x);
154                 /* Execute script */
155                 execl(script, script, args, (char *)NULL);
156                 /* Can't use ast_log since FD's are closed */
157                 fprintf(stderr, "Failed to execute '%s': %s\n", script, strerror(errno));
158                 exit(1);
159         }
160         if (option_verbose > 2) 
161                 ast_verbose(VERBOSE_PREFIX_3 "Launched AGI Script %s\n", script);
162         fds[0] = toast[0];
163         fds[1] = fromast[1];
164         if (efd) {
165                 *efd = audio[1];
166         }
167         /* close what we're not using in the parent */
168         close(toast[1]);
169         close(fromast[0]);
170         *opid = pid;
171         return 0;
172                 
173 }
174
175 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced)
176 {
177         /* Print initial environment, with agi_request always being the first
178            thing */
179         fdprintf(fd, "agi_request: %s\n", request);
180         fdprintf(fd, "agi_channel: %s\n", chan->name);
181         fdprintf(fd, "agi_language: %s\n", chan->language);
182         fdprintf(fd, "agi_type: %s\n", chan->type);
183         fdprintf(fd, "agi_uniqueid: %s\n", chan->uniqueid);
184
185         /* ANI/DNIS */
186         fdprintf(fd, "agi_callerid: %s\n", chan->callerid ? chan->callerid : "unknown");
187         fdprintf(fd, "agi_dnid: %s\n", chan->dnid ? chan->dnid : "unknown");
188         fdprintf(fd, "agi_rdnis: %s\n", chan->rdnis ? chan->rdnis : "unknown");
189
190         /* Context information */
191         fdprintf(fd, "agi_context: %s\n", chan->context);
192         fdprintf(fd, "agi_extension: %s\n", chan->exten);
193         fdprintf(fd, "agi_priority: %d\n", chan->priority);
194         fdprintf(fd, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
195
196     /* User information */
197     fdprintf(fd, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
198     
199         /* End with empty return */
200         fdprintf(fd, "\n");
201 }
202
203 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
204 {
205         int res;
206         res = 0;
207         if (chan->_state != AST_STATE_UP) {
208                 /* Answer the chan */
209                 res = ast_answer(chan);
210         }
211         fdprintf(agi->fd, "200 result=%d\n", res);
212         if (res >= 0)
213                 return RESULT_SUCCESS;
214         else
215                 return RESULT_FAILURE;
216 }
217
218 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
219 {
220         int res;
221         int to;
222         if (argc != 4)
223                 return RESULT_SHOWUSAGE;
224         if (sscanf(argv[3], "%i", &to) != 1)
225                 return RESULT_SHOWUSAGE;
226         res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
227         fdprintf(agi->fd, "200 result=%d\n", res);
228         if (res >= 0)
229                 return RESULT_SUCCESS;
230         else
231                 return RESULT_FAILURE;
232 }
233
234 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
235 {
236         int res;
237         if (argc != 3)
238                 return RESULT_SHOWUSAGE;
239         /* At the moment, the parser (perhaps broken) returns with
240            the last argument PLUS the newline at the end of the input
241            buffer. This probably needs to be fixed, but I wont do that
242            because other stuff may break as a result. The right way
243            would probably be to strip off the trailing newline before
244            parsing, then here, add a newline at the end of the string
245            before sending it to ast_sendtext --DUDE */
246         res = ast_sendtext(chan, argv[2]);
247         fdprintf(agi->fd, "200 result=%d\n", res);
248         if (res >= 0)
249                 return RESULT_SUCCESS;
250         else
251                 return RESULT_FAILURE;
252 }
253
254 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
255 {
256         int res;
257         if (argc != 3)
258                 return RESULT_SHOWUSAGE;
259         res = ast_recvchar(chan,atoi(argv[2]));
260         if (res == 0) {
261                 fdprintf(agi->fd, "200 result=%d (timeout)\n", res);
262                 return RESULT_SUCCESS;
263         }
264         if (res > 0) {
265                 fdprintf(agi->fd, "200 result=%d\n", res);
266                 return RESULT_SUCCESS;
267         }
268         else {
269                 fdprintf(agi->fd, "200 result=%d (hangup)\n", res);
270                 return RESULT_FAILURE;
271         }
272 }
273
274 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
275 {
276         int res,x;
277         if (argc != 3)
278                 return RESULT_SHOWUSAGE;
279         if (!strncasecmp(argv[2],"on",2)) x = 1; else x = 0;
280         if (!strncasecmp(argv[2],"mate",4)) x = 2;
281         if (!strncasecmp(argv[2],"tdd",3)) x = 1;
282         res = ast_channel_setoption(chan,AST_OPTION_TDD,&x,sizeof(char),0);
283         fdprintf(agi->fd, "200 result=%d\n", res);
284         if (res >= 0) 
285                 return RESULT_SUCCESS;
286         else
287                 return RESULT_FAILURE;
288 }
289
290 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
291 {
292         int res;
293         if (argc != 3)
294                 return RESULT_SHOWUSAGE;
295         res = ast_send_image(chan, argv[2]);
296         if (!ast_check_hangup(chan))
297                 res = 0;
298         fdprintf(agi->fd, "200 result=%d\n", res);
299         if (res >= 0)
300                 return RESULT_SUCCESS;
301         else
302                 return RESULT_FAILURE;
303 }
304
305 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
306 {
307         int res;
308         struct ast_filestream *fs;
309         long sample_offset = 0;
310         long max_length;
311
312         if (argc < 4)
313                 return RESULT_SHOWUSAGE;
314         if (argc > 5)
315                 return RESULT_SHOWUSAGE;
316         if ((argc > 4) && (sscanf(argv[4], "%ld", &sample_offset) != 1))
317                 return RESULT_SHOWUSAGE;
318         
319         fs = ast_openstream(chan, argv[2], chan->language);
320         if(!fs){
321                 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
322                 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
323                 return RESULT_FAILURE;
324         }
325         ast_seekstream(fs, 0, SEEK_END);
326         max_length = ast_tellstream(fs);
327         ast_seekstream(fs, sample_offset, SEEK_SET);
328         res = ast_applystream(chan, fs);
329         res = ast_playstream(fs);
330         if (res) {
331                 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
332                 if (res >= 0)
333                         return RESULT_SHOWUSAGE;
334                 else
335                         return RESULT_FAILURE;
336         }
337         res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
338         /* this is to check for if ast_waitstream closed the stream, we probably are at
339          * the end of the stream, return that amount, else check for the amount */
340         sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
341         ast_stopstream(chan);
342         if (res == 1) {
343                 /* Stop this command, don't print a result line, as there is a new command */
344                 return RESULT_SUCCESS;
345         }
346         fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
347         if (res >= 0)
348                 return RESULT_SUCCESS;
349         else
350                 return RESULT_FAILURE;
351 }
352
353 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
354 {
355         int res;
356         int num;
357         if (argc != 4)
358                 return RESULT_SHOWUSAGE;
359         if (sscanf(argv[2], "%i", &num) != 1)
360                 return RESULT_SHOWUSAGE;
361         res = ast_say_number_full(chan, num, argv[3], chan->language, agi->audio, agi->ctrl);
362         if (res == 1)
363                 return RESULT_SUCCESS;
364         fdprintf(agi->fd, "200 result=%d\n", res);
365         if (res >= 0)
366                 return RESULT_SUCCESS;
367         else
368                 return RESULT_FAILURE;
369 }
370
371 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
372 {
373         int res;
374         int num;
375         if (argc != 4)
376                 return RESULT_SHOWUSAGE;
377         if (sscanf(argv[2], "%i", &num) != 1)
378                 return RESULT_SHOWUSAGE;
379         res = ast_say_digit_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
380         if (res == 1) /* New command */
381                 return RESULT_SUCCESS;
382         fdprintf(agi->fd, "200 result=%d\n", res);
383         if (res >= 0)
384                 return RESULT_SUCCESS;
385         else
386                 return RESULT_FAILURE;
387 }
388
389 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
390 {
391         int res;
392         char data[1024];
393         int max;
394         int timeout;
395
396         if (argc < 3)
397                 return RESULT_SHOWUSAGE;
398         if (argc >= 4) timeout = atoi(argv[3]); else timeout = 0;
399         if (argc >= 5) max = atoi(argv[4]); else max = 1024;
400         res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
401         if (res == 2)                   /* New command */
402                 return RESULT_SUCCESS;
403         else if (res == 1)
404                 fdprintf(agi->fd, "200 result=%s (timeout)\n", data);
405     else if (res < 0 )
406         fdprintf(agi->fd, "200 result=-1\n");
407         else
408                 fdprintf(agi->fd, "200 result=%s\n", data);
409         if (res >= 0)
410                 return RESULT_SUCCESS;
411         else
412                 return RESULT_FAILURE;
413 }
414
415 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
416 {
417
418         if (argc != 3)
419                 return RESULT_SHOWUSAGE;
420         strncpy(chan->context, argv[2], sizeof(chan->context)-1);
421         fdprintf(agi->fd, "200 result=0\n");
422         return RESULT_SUCCESS;
423 }
424         
425 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, char **argv)
426 {
427         if (argc != 3)
428                 return RESULT_SHOWUSAGE;
429         strncpy(chan->exten, argv[2], sizeof(chan->exten)-1);
430         fdprintf(agi->fd, "200 result=0\n");
431         return RESULT_SUCCESS;
432 }
433
434 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char **argv)
435 {
436         int pri;
437         if (argc != 3)
438                 return RESULT_SHOWUSAGE;        
439         if (sscanf(argv[2], "%i", &pri) != 1)
440                 return RESULT_SHOWUSAGE;
441         chan->priority = pri - 1;
442         fdprintf(agi->fd, "200 result=0\n");
443         return RESULT_SUCCESS;
444 }
445                 
446 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
447 {
448         struct ast_filestream *fs;
449         struct ast_frame *f;
450         struct timeval tv, start;
451         long sample_offset = 0;
452         int res = 0;
453         int ms;
454
455         struct ast_dsp *sildet=NULL;         /* silence detector dsp */
456         int totalsilence = 0;
457         int dspsilence = 0;
458         int silence = 0;                /* amount of silence to allow */
459         int gotsilence = 0;             /* did we timeout for silence? */
460         char *silencestr=NULL;
461         int rfmt=0;
462
463
464         /* XXX EAGI FIXME XXX */
465
466         if (argc < 6)
467                 return RESULT_SHOWUSAGE;
468         if (sscanf(argv[5], "%i", &ms) != 1)
469                 return RESULT_SHOWUSAGE;
470
471         if (argc > 6)
472                 silencestr = strchr(argv[6],'s');
473         if ((argc > 7) && (!silencestr))
474                 silencestr = strchr(argv[7],'s');
475         if ((argc > 8) && (!silencestr))
476                 silencestr = strchr(argv[8],'s');
477
478         if (silencestr) {
479                 if (strlen(silencestr) > 2) {
480                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
481                                 silencestr++;
482                                 silencestr++;
483                                 if (silencestr)
484                                         silence = atoi(silencestr);
485                                 if (silence > 0)
486                                         silence *= 1000;
487                         }
488                 }
489         }
490
491         if (silence > 0) {
492                 rfmt = chan->readformat;
493                 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
494                 if (res < 0) {
495                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
496                         return -1;
497                 }
498                 sildet = ast_dsp_new();
499                 if (!sildet) {
500                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
501                         return -1;
502                 }
503                 ast_dsp_set_threshold(sildet, 256);
504         }
505
506         /* backward compatibility, if no offset given, arg[6] would have been
507          * caught below and taken to be a beep, else if it is a digit then it is a
508          * offset */
509         if ((argc >6) && (sscanf(argv[6], "%ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
510                 res = ast_streamfile(chan, "beep", chan->language);
511
512         if ((argc > 7) && (!strchr(argv[7], '=')))
513                 res = ast_streamfile(chan, "beep", chan->language);
514
515         if (!res)
516                 res = ast_waitstream(chan, argv[4]);
517         if (!res) {
518                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY, 0, 0644);
519                 if (!fs) {
520                         res = -1;
521                         fdprintf(agi->fd, "200 result=%d (writefile)\n", res);
522                         return RESULT_FAILURE;
523                 }
524                 
525                 chan->stream = fs;
526                 ast_applystream(chan,fs);
527                 /* really should have checks */
528                 ast_seekstream(fs, sample_offset, SEEK_SET);
529                 ast_truncstream(fs);
530                 
531                 gettimeofday(&start, NULL);
532                 gettimeofday(&tv, NULL);
533                 while ((ms < 0) || (((tv.tv_sec - start.tv_sec) * 1000 + (tv.tv_usec - start.tv_usec)/1000) < ms)) {
534                         res = ast_waitfor(chan, -1);
535                         if (res < 0) {
536                                 ast_closestream(fs);
537                                 fdprintf(agi->fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
538                                 return RESULT_FAILURE;
539                         }
540                         f = ast_read(chan);
541                         if (!f) {
542                                 fdprintf(agi->fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
543                                 ast_closestream(fs);
544                                 return RESULT_FAILURE;
545                         }
546                         switch(f->frametype) {
547                         case AST_FRAME_DTMF:
548                                 if (strchr(argv[4], f->subclass)) {
549                                         /* This is an interrupting chracter */
550                                         sample_offset = ast_tellstream(fs);
551                                         fdprintf(agi->fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
552                                         ast_closestream(fs);
553                                         ast_frfree(f);
554                                         return RESULT_SUCCESS;
555                                 }
556                                 break;
557                         case AST_FRAME_VOICE:
558                                 ast_writestream(fs, f);
559                                 /* this is a safe place to check progress since we know that fs
560                                  * is valid after a write, and it will then have our current
561                                  * location */
562                                 sample_offset = ast_tellstream(fs);
563                                 if (silence > 0) {
564                                         dspsilence = 0;
565                                         ast_dsp_silence(sildet, f, &dspsilence);
566                                         if (dspsilence) {
567                                                 totalsilence = dspsilence;
568                                         } else {
569                                                 totalsilence = 0;
570                                         }
571                                         if (totalsilence > silence) {
572                                              /* Ended happily with silence */
573                                                 ast_frfree(f);
574                                                 gotsilence = 1;
575                                                 break;
576                                         }
577                                 }
578                                 break;
579                         }
580                         ast_frfree(f);
581                         gettimeofday(&tv, NULL);
582                         if (gotsilence)
583                                 break;
584         }
585
586                 if (gotsilence) {
587                         ast_stream_rewind(fs, silence-1000);
588                         ast_truncstream(fs);
589                 }               
590                 fdprintf(agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
591                 ast_closestream(fs);
592         } else
593                 fdprintf(agi->fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
594
595         if (silence > 0) {
596                 res = ast_set_read_format(chan, rfmt);
597                 if (res)
598                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
599                 ast_dsp_free(sildet);
600         }
601         return RESULT_SUCCESS;
602 }
603
604 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
605 {
606         int timeout;
607
608         if (argc != 3)
609                 return RESULT_SHOWUSAGE;
610         if (sscanf(argv[2], "%d", &timeout) != 1)
611                 return RESULT_SHOWUSAGE;
612         if (timeout < 0)
613                 timeout = 0;
614         if (timeout)
615                 chan->whentohangup = time(NULL) + timeout;
616         else
617                 chan->whentohangup = 0;
618         fdprintf(agi->fd, "200 result=0\n");
619         return RESULT_SUCCESS;
620 }
621
622 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **argv)
623 {
624         struct ast_channel *c;
625         if (argc==1) {
626             /* no argument: hangup the current channel */
627             ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
628             fdprintf(agi->fd, "200 result=1\n");
629             return RESULT_SUCCESS;
630         } else if (argc==2) {
631             /* one argument: look for info on the specified channel */
632             c = ast_channel_walk(NULL);
633             while (c) {
634                 if (strcasecmp(argv[1],c->name)==0) {
635                     /* we have a matching channel */
636                     ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
637                     fdprintf(agi->fd, "200 result=1\n");
638                     return RESULT_SUCCESS;
639                 }
640                 c = ast_channel_walk(c);
641             }
642             /* if we get this far no channel name matched the argument given */
643             fdprintf(agi->fd, "200 result=-1\n");
644             return RESULT_SUCCESS;
645         } else {
646             return RESULT_SHOWUSAGE;
647         }
648 }
649
650 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, char **argv)
651 {
652         int res;
653         struct ast_app *app;
654
655         if (argc < 2)
656                 return RESULT_SHOWUSAGE;
657
658         if (option_verbose > 2)
659                 ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
660
661         app = pbx_findapp(argv[1]);
662
663         if (app) {
664                 res = pbx_exec(chan, app, argv[2], 1);
665         } else {
666                 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
667                 res = -2;
668         }
669         fdprintf(agi->fd, "200 result=%d\n", res);
670
671         return res;
672 }
673
674 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, char **argv)
675 {
676         if (argv[2])
677                 ast_set_callerid(chan, argv[2], 0);
678
679 /*      strncpy(chan->callerid, argv[2], sizeof(chan->callerid)-1);
680 */      fdprintf(agi->fd, "200 result=1\n");
681         return RESULT_SUCCESS;
682 }
683
684 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, char **argv)
685 {
686         struct ast_channel *c;
687         if (argc==2) {
688             /* no argument: supply info on the current channel */
689             fdprintf(agi->fd, "200 result=%d\n", chan->_state);
690             return RESULT_SUCCESS;
691         } else if (argc==3) {
692             /* one argument: look for info on the specified channel */
693             c = ast_channel_walk(NULL);
694             while (c) {
695                 if (strcasecmp(argv[2],c->name)==0) {
696                     fdprintf(agi->fd, "200 result=%d\n", c->_state);
697                     return RESULT_SUCCESS;
698                 }
699                 c = ast_channel_walk(c);
700             }
701             /* if we get this far no channel name matched the argument given */
702             fdprintf(agi->fd, "200 result=-1\n");
703             return RESULT_SUCCESS;
704         } else {
705             return RESULT_SHOWUSAGE;
706         }
707 }
708
709 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
710 {
711         if (argv[3])
712                 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
713
714         fdprintf(agi->fd, "200 result=1\n");
715         return RESULT_SUCCESS;
716 }
717
718 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
719 {
720         char *tempstr;
721
722         if ((tempstr = pbx_builtin_getvar_helper(chan, argv[2])) ) 
723                         fdprintf(agi->fd, "200 result=1 (%s)\n", tempstr);
724         else
725                         fdprintf(agi->fd, "200 result=0\n");
726
727         return RESULT_SUCCESS;
728 }
729
730 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **argv)
731 {
732         int level = 0;
733         char *prefix;
734
735         if (argc < 2)
736                 return RESULT_SHOWUSAGE;
737
738         if (argv[2])
739                 sscanf(argv[2], "%d", &level);
740
741         switch (level) {
742                 case 4:
743                         prefix = VERBOSE_PREFIX_4;
744                         break;
745                 case 3:
746                         prefix = VERBOSE_PREFIX_3;
747                         break;
748                 case 2:
749                         prefix = VERBOSE_PREFIX_2;
750                         break;
751                 case 1:
752                 default:
753                         prefix = VERBOSE_PREFIX_1;
754                         break;
755         }
756
757         if (level <= option_verbose)
758                 ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
759         
760         fdprintf(agi->fd, "200 result=1\n");
761         
762         return RESULT_SUCCESS;
763 }
764
765 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, char **argv)
766 {
767         int res;
768         char tmp[256];
769         if (argc != 4)
770                 return RESULT_SHOWUSAGE;
771         res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
772         if (res) 
773                         fdprintf(agi->fd, "200 result=0\n");
774         else
775                         fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
776
777         return RESULT_SUCCESS;
778 }
779
780 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, char **argv)
781 {
782         int res;
783         if (argc != 5)
784                 return RESULT_SHOWUSAGE;
785         res = ast_db_put(argv[2], argv[3], argv[4]);
786         if (res) 
787                         fdprintf(agi->fd, "200 result=0\n");
788         else
789                         fdprintf(agi->fd, "200 result=1\n");
790
791         return RESULT_SUCCESS;
792 }
793
794 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, char **argv)
795 {
796         int res;
797         if (argc != 4)
798                 return RESULT_SHOWUSAGE;
799         res = ast_db_del(argv[2], argv[3]);
800         if (res) 
801                 fdprintf(agi->fd, "200 result=0\n");
802         else
803                 fdprintf(agi->fd, "200 result=1\n");
804
805         return RESULT_SUCCESS;
806 }
807
808 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char **argv)
809 {
810         int res;
811         if ((argc < 3) || (argc > 4))
812                 return RESULT_SHOWUSAGE;
813         if (argc == 4)
814                 res = ast_db_deltree(argv[2], argv[3]);
815         else
816                 res = ast_db_deltree(argv[2], NULL);
817
818         if (res) 
819                 fdprintf(agi->fd, "200 result=0\n");
820         else
821                 fdprintf(agi->fd, "200 result=1\n");
822         return RESULT_SUCCESS;
823 }
824
825 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
826 {
827         fdprintf(agi->fd, "200 result=0\n");
828         return RESULT_SUCCESS;
829 }
830
831 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
832 {
833         if (!strncasecmp(argv[2],"on",2)) {
834                 if (argc > 3)
835                         ast_moh_start(chan, argv[3]);
836                 else
837                         ast_moh_start(chan, NULL);
838         }
839         if (!strncasecmp(argv[2],"off",3)) {
840                 ast_moh_stop(chan);
841         }
842         fdprintf(agi->fd, "200 result=0\n");
843         return RESULT_SUCCESS;
844 }
845
846 static char usage_setmusic[] =
847 " Usage: SET MUSIC ON <on|off> <class>\n"
848 "       Enables/Disables the music on hold generator.  If <class> is\n"
849 " not specified then the default music on hold class will be used.\n"
850 " Always returns 0\n";
851
852 static char usage_dbput[] =
853 " Usage: DATABASE PUT <family> <key> <value>\n"
854 "       Adds or updates an entry in the Asterisk database for a\n"
855 " given family, key, and value.\n"
856 " Returns 1 if succesful, 0 otherwise\n";
857
858 static char usage_dbget[] =
859 " Usage: DATABASE GET <family> <key>\n"
860 "       Retrieves an entry in the Asterisk database for a\n"
861 " given family and key.\n"
862 "       Returns 0 if <key> is not set.  Returns 1 if <key>\n"
863 " is set and returns the variable in parenthesis\n"
864 " example return code: 200 result=1 (testvariable)\n";
865
866 static char usage_dbdel[] =
867 " Usage: DATABASE DEL <family> <key>\n"
868 "       Deletes an entry in the Asterisk database for a\n"
869 " given family and key.\n"
870 " Returns 1 if succesful, 0 otherwise\n";
871
872 static char usage_dbdeltree[] =
873 " Usage: DATABASE DELTREE <family> [keytree]\n"
874 "       Deletes a family or specific keytree withing a family\n"
875 " in the Asterisk database.\n"
876 " Returns 1 if succesful, 0 otherwise\n";
877
878 static char usage_verbose[] =
879 " Usage: VERBOSE <message> <level>\n"
880 "       Sends <message> to the console via verbose message system.\n"
881 "       <level> is the the verbose level (1-4)\n"
882 "       Always returns 1\n";
883
884 static char usage_getvariable[] =
885 " Usage: GET VARIABLE <variablename>\n"
886 "       Returns 0 if <variablename> is not set.  Returns 1 if <variablename>\n"
887 " is set and returns the variable in parenthesis\n"
888 " example return code: 200 result=1 (testvariable)\n";
889
890 static char usage_setvariable[] =
891 " Usage: SET VARIABLE <variablename> <value>\n";
892
893 static char usage_channelstatus[] =
894 " Usage: CHANNEL STATUS [<channelname>]\n"
895 "       Returns the status of the specified channel.\n" 
896 "       If no channel name is given the returns the status of the\n"
897 "       current channel.\n"
898 "       Return values:\n"
899 " 0 Channel is down and available\n"
900 " 1 Channel is down, but reserved\n"
901 " 2 Channel is off hook\n"
902 " 3 Digits (or equivalent) have been dialed\n"
903 " 4 Line is ringing\n"
904 " 5 Remote end is ringing\n"
905 " 6 Line is up\n"
906 " 7 Line is busy\n";
907
908 static char usage_setcallerid[] =
909 " Usage: SET CALLERID <number>\n"
910 "       Changes the callerid of the current channel.\n";
911
912 static char usage_exec[] =
913 " Usage: EXEC <application> <options>\n"
914 "       Executes <application> with given <options>.\n"
915 "       Returns whatever the application returns, or -2 on failure to find application\n";
916
917 static char usage_hangup[] =
918 " Usage: HANGUP [<channelname>]\n"
919 "       Hangs up the specified channel.\n"
920 "       If no channel name is given, hangs up the current channel\n";
921
922 static char usage_answer[] = 
923 " Usage: ANSWER\n"
924 "        Answers channel if not already in answer state. Returns -1 on\n"
925 " channel failure, or 0 if successful.\n";
926
927 static char usage_waitfordigit[] = 
928 " Usage: WAIT FOR DIGIT <timeout>\n"
929 "        Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
930 " Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
931 " the numerical value of the ascii of the digit if one is received.  Use -1\n"
932 " for the timeout value if you desire the call to block indefinitely.\n";
933
934 static char usage_sendtext[] =
935 " Usage: SEND TEXT \"<text to send>\"\n"
936 "        Sends the given text on a channel.  Most channels do not support the\n"
937 " transmission of text.  Returns 0 if text is sent, or if the channel does not\n"
938 " support text transmission.  Returns -1 only on error/hangup.  Text\n"
939 " consisting of greater than one word should be placed in quotes since the\n"
940 " command only accepts a single argument.\n";
941
942 static char usage_recvchar[] =
943 " Usage: RECEIVE CHAR <timeout>\n"
944 "        Receives a character of text on a channel.  Specify timeout to be the\n"
945 " maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
946 " do not support the reception of text.  Returns the decimal value of the character\n"
947 " if one is received, or 0 if the channel does not support text reception.  Returns\n"
948 " -1 only on error/hangup.\n";
949
950 static char usage_tddmode[] =
951 " Usage: TDD MODE <on|off>\n"
952 "        Enable/Disable TDD transmission/reception on a channel. Returns 1 if\n"
953 " successful, or 0 if channel is not TDD-capable.\n";
954
955 static char usage_sendimage[] =
956 " Usage: SEND IMAGE <image>\n"
957 "        Sends the given image on a channel.  Most channels do not support the\n"
958 " transmission of images.  Returns 0 if image is sent, or if the channel does not\n"
959 " support image transmission.  Returns -1 only on error/hangup.  Image names\n"
960 " should not include extensions.\n";
961
962 static char usage_streamfile[] =
963 " Usage: STREAM FILE <filename> <escape digits> [sample offset]\n"
964 "        Send the given file, allowing playback to be interrupted by the given\n"
965 " digits, if any.  Use double quotes for the digits if you wish none to be\n"
966 " permitted.  If sample offset is provided then the audio will seek to sample\n"
967 " offset before play starts.  Returns 0 if playback completes without a digit\n"
968 " being pressed, or the ASCII numerical value of the digit if one was pressed,\n"
969 " or -1 on error or if the channel was disconnected.  Remember, the file\n"
970 " extension must not be included in the filename.\n";
971
972 static char usage_saynumber[] =
973 " Usage: SAY NUMBER <number> <escape digits>\n"
974 "        Say a given number, returning early if any of the given DTMF digits\n"
975 " are received on the channel.  Returns 0 if playback completes without a digit\n"
976 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
977 " -1 on error/hangup.\n";
978
979 static char usage_saydigits[] =
980 " Usage: SAY DIGITS <number> <escape digits>\n"
981 "        Say a given digit string, returning early if any of the given DTMF digits\n"
982 " are received on the channel.  Returns 0 if playback completes without a digit\n"
983 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
984 " -1 on error/hangup.\n";
985
986 static char usage_getdata[] =
987 " Usage: GET DATA <file to be streamed> [timeout] [max digits]\n"
988 "        Stream the given file, and recieve DTMF data. Returns the digits recieved\n"
989 "from the channel at the other end.\n";
990
991 static char usage_setcontext[] =
992 " Usage: SET CONTEXT <desired context>\n"
993 "        Sets the context for continuation upon exiting the application.\n";
994
995 static char usage_setextension[] =
996 " Usage: SET EXTENSION <new extension>\n"
997 "        Changes the extension for continuation upon exiting the application.\n";
998
999 static char usage_setpriority[] =
1000 " Usage: SET PRIORITY <num>\n"
1001 "        Changes the priority for continuation upon exiting the application.\n";
1002
1003 static char usage_recordfile[] =
1004 " Usage: RECORD FILE <filename> <format> <escape digits> <timeout> [offset samples] [BEEP] [s=silence]\n"
1005 "        Record to a file until a given dtmf digit in the sequence is received\n"
1006 " Returns -1 on hangup or error.  The format will specify what kind of file\n"
1007 " will be recorded.  The timeout is the maximum record time in milliseconds, or\n"
1008 " -1 for no timeout. Offset samples is optional, and if provided will seek to\n"
1009 " the offset without exceeding the end of the file.  \"silence\" is the number\n"
1010 " of seconds of silence allowed before the function returns despite the\n"
1011 " lack of dtmf digits or reaching timeout.  Silence value must be\n"
1012 " preceeded by \"s=\" and is optional.\n";
1013
1014
1015 static char usage_autohangup[] =
1016 " Usage: SET AUTOHANGUP <time>\n"
1017 "    Cause the channel to automatically hangup at <time> seconds in the\n"
1018 "future.  Of course it can be hungup before then as well.   Setting to\n"
1019 "0 will cause the autohangup feature to be disabled on this channel.\n";
1020
1021 static char usage_noop[] =
1022 " Usage: NOOP\n"
1023 "    Does nothing.\n";
1024
1025 static agi_command commands[] = {
1026         { { "answer", NULL }, handle_answer, "Asserts answer", usage_answer },
1027         { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
1028         { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
1029         { { "receive", "char", NULL }, handle_recvchar, "Receives text from channels supporting it", usage_recvchar },
1030         { { "tdd", "mode", NULL }, handle_tddmode, "Sends text to channels supporting it", usage_tddmode },
1031         { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
1032         { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
1033         { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
1034         { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
1035         { { "get", "data", NULL }, handle_getdata, "Gets data on a channel", usage_getdata },
1036         { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
1037         { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
1038         { { "set", "priority", NULL }, handle_setpriority, "Prioritizes the channel", usage_setpriority },
1039         { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
1040         { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
1041         { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
1042         { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
1043         { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
1044         { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus },
1045         { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable },
1046         { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable },
1047         { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose },
1048         { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget },
1049         { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput },
1050         { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel },
1051         { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree },
1052         { { "noop", NULL }, handle_noop, "Does nothing", usage_noop },
1053         { { "set", "music", NULL }, handle_setmusic, "Enable/Disable Music on hold generator", usage_setmusic }
1054 };
1055
1056 static void join(char *s, int len, char *w[])
1057 {
1058         int x;
1059         /* Join words into a string */
1060         strcpy(s, "");
1061         for (x=0;w[x];x++) {
1062                 if (x)
1063                         strncat(s, " ", len - strlen(s));
1064                 strncat(s, w[x], len - strlen(s));
1065         }
1066 }
1067
1068 static int help_workhorse(int fd, char *match[])
1069 {
1070         char fullcmd[80];
1071         char matchstr[80];
1072         int x;
1073         struct agi_command *e;
1074         if (match)
1075                 join(matchstr, sizeof(matchstr), match);
1076         for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1077                 e = &commands[x]; 
1078                 if (e)
1079                         join(fullcmd, sizeof(fullcmd), e->cmda);
1080                 /* Hide commands that start with '_' */
1081                 if (fullcmd[0] == '_')
1082                         continue;
1083                 if (match) {
1084                         if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1085                                 continue;
1086                         }
1087                 }
1088                 ast_cli(fd, "%20.20s   %s\n", fullcmd, e->summary);
1089         }
1090         return 0;
1091 }
1092
1093 static agi_command *find_command(char *cmds[], int exact)
1094 {
1095         int x;
1096         int y;
1097         int match;
1098         for (x=0;x < sizeof(commands) / sizeof(commands[0]);x++) {
1099                 /* start optimistic */
1100                 match = 1;
1101                 for (y=0;match && cmds[y]; y++) {
1102                         /* If there are no more words in the command (and we're looking for
1103                            an exact match) or there is a difference between the two words,
1104                            then this is not a match */
1105                         if (!commands[x].cmda[y] && !exact)
1106                                 break;
1107                         /* don't segfault if the next part of a command doesn't exist */
1108                         if (!commands[x].cmda[y]) return NULL;
1109                         if (strcasecmp(commands[x].cmda[y], cmds[y]))
1110                                 match = 0;
1111                 }
1112                 /* If more words are needed to complete the command then this is not
1113                    a candidate (unless we're looking for a really inexact answer  */
1114                 if ((exact > -1) && commands[x].cmda[y])
1115                         match = 0;
1116                 if (match)
1117                         return &commands[x];
1118         }
1119         return NULL;
1120 }
1121
1122
1123 static int parse_args(char *s, int *max, char *argv[])
1124 {
1125         int x=0;
1126         int quoted=0;
1127         int escaped=0;
1128         int whitespace=1;
1129         char *cur;
1130
1131         cur = s;
1132         while(*s) {
1133                 switch(*s) {
1134                 case '"':
1135                         /* If it's escaped, put a literal quote */
1136                         if (escaped) 
1137                                 goto normal;
1138                         else 
1139                                 quoted = !quoted;
1140                         if (quoted && whitespace) {
1141                                 /* If we're starting a quote, coming off white space start a new word, too */
1142                                 argv[x++] = cur;
1143                                 whitespace=0;
1144                         }
1145                         escaped = 0;
1146                 break;
1147                 case ' ':
1148                 case '\t':
1149                         if (!quoted && !escaped) {
1150                                 /* If we're not quoted, mark this as whitespace, and
1151                                    end the previous argument */
1152                                 whitespace = 1;
1153                                 *(cur++) = '\0';
1154                         } else
1155                                 /* Otherwise, just treat it as anything else */ 
1156                                 goto normal;
1157                         break;
1158                 case '\\':
1159                         /* If we're escaped, print a literal, otherwise enable escaping */
1160                         if (escaped) {
1161                                 goto normal;
1162                         } else {
1163                                 escaped=1;
1164                         }
1165                         break;
1166                 default:
1167 normal:
1168                         if (whitespace) {
1169                                 if (x >= MAX_ARGS -1) {
1170                                         ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1171                                         break;
1172                                 }
1173                                 /* Coming off of whitespace, start the next argument */
1174                                 argv[x++] = cur;
1175                                 whitespace=0;
1176                         }
1177                         *(cur++) = *s;
1178                         escaped=0;
1179                 }
1180                 s++;
1181         }
1182         /* Null terminate */
1183         *(cur++) = '\0';
1184         argv[x] = NULL;
1185         *max = x;
1186         return 0;
1187 }
1188
1189 static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf)
1190 {
1191         char *argv[MAX_ARGS];
1192         int argc = 0;
1193         int res;
1194         agi_command *c;
1195         argc = MAX_ARGS;
1196         parse_args(buf, &argc, argv);
1197 #if     0
1198         { int x;
1199         for (x=0;x<argc;x++) 
1200                 fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
1201 #endif
1202         c = find_command(argv, 0);
1203         if (c) {
1204                 res = c->handler(chan, agi, argc, argv);
1205                 switch(res) {
1206                 case RESULT_SHOWUSAGE:
1207                         fdprintf(agi->fd, "520-Invalid command syntax.  Proper usage follows:\n");
1208                         fdprintf(agi->fd, c->usage);
1209                         fdprintf(agi->fd, "520 End of proper usage.\n");
1210                         break;
1211                 case RESULT_FAILURE:
1212                         /* They've already given the failure.  We've been hung up on so handle this
1213                            appropriately */
1214                         return -1;
1215                 }
1216         } else {
1217                 fdprintf(agi->fd, "510 Invalid or unknown command\n");
1218         }
1219         return 0;
1220 }
1221
1222 static int run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid)
1223 {
1224         struct ast_channel *c;
1225         int outfd;
1226         int ms;
1227         int returnstatus = 0;
1228         struct ast_frame *f;
1229         char buf[2048];
1230         FILE *readf;
1231         if (!(readf = fdopen(agi->ctrl, "r"))) {
1232                 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
1233                 kill(pid, SIGHUP);
1234                 return -1;
1235         }
1236         setlinebuf(readf);
1237         setup_env(chan, request, agi->fd, (agi->audio > -1));
1238         for (;;) {
1239                 ms = -1;
1240                 c = ast_waitfor_nandfds(&chan, 1, &agi->ctrl, 1, NULL, &outfd, &ms);
1241                 if (c) {
1242                         /* Idle the channel until we get a command */
1243                         f = ast_read(c);
1244                         if (!f) {
1245                                 ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
1246                                 returnstatus = -1;
1247                                 break;
1248                         } else {
1249                                 /* If it's voice, write it to the audio pipe */
1250                                 if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
1251                                         /* Write, ignoring errors */
1252                                         write(agi->audio, f->data, f->datalen);
1253                                 }
1254                                 ast_frfree(f);
1255                         }
1256                 } else if (outfd > -1) {
1257                         if (!fgets(buf, sizeof(buf), readf)) {
1258                                 /* Program terminated */
1259                                 if (returnstatus)
1260                                         returnstatus = -1;
1261                                 if (option_verbose > 2) 
1262                                         ast_verbose(VERBOSE_PREFIX_3 "AGI Script %s completed, returning %d\n", request, returnstatus);
1263                                 /* No need to kill the pid anymore, since they closed us */
1264                                 pid = -1;
1265                                 break;
1266                         }
1267                           /* get rid of trailing newline, if any */
1268                         if (*buf && buf[strlen(buf) - 1] == '\n')
1269                                 buf[strlen(buf) - 1] = 0;
1270
1271                         returnstatus |= agi_handle_command(chan, agi, buf);
1272                         /* If the handle_command returns -1, we need to stop */
1273                         if (returnstatus < 0) {
1274                                 break;
1275                         }
1276                 } else {
1277                         ast_log(LOG_WARNING, "No channel, no fd?\n");
1278                         returnstatus = -1;
1279                         break;
1280                 }
1281         }
1282         /* Notify process */
1283         if (pid > -1)
1284                 kill(pid, SIGHUP);
1285         fclose(readf);
1286         return returnstatus;
1287 }
1288
1289 static int handle_showagi(int fd, int argc, char *argv[]) {
1290         struct agi_command *e;
1291         char fullcmd[80];
1292         if ((argc < 2))
1293                 return RESULT_SHOWUSAGE;
1294         if (argc > 2) {
1295                 e = find_command(argv + 2, 1);
1296                 if (e) 
1297                         ast_cli(fd, e->usage);
1298                 else {
1299                         if (find_command(argv + 2, -1)) {
1300                                 return help_workhorse(fd, argv + 1);
1301                         } else {
1302                                 join(fullcmd, sizeof(fullcmd), argv+1);
1303                                 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1304                         }
1305                 }
1306         } else {
1307                 return help_workhorse(fd, NULL);
1308         }
1309         return RESULT_SUCCESS;
1310 }
1311
1312 static int handle_dumpagihtml(int fd, int argc, char *argv[]) {
1313         struct agi_command *e;
1314         char fullcmd[80];
1315         char *tempstr;
1316         int x;
1317         FILE *htmlfile;
1318
1319         if ((argc < 3))
1320                 return RESULT_SHOWUSAGE;
1321
1322         if (!(htmlfile = fopen(argv[2], "wt"))) {
1323                 ast_cli(fd, "Could not create file '%s'\n", argv[2]);
1324                 return RESULT_SHOWUSAGE;
1325         }
1326
1327         fprintf(htmlfile, "<HTML>\n<HEAD>\n<TITLE>AGI Commands</TITLE>\n</HEAD>\n");
1328         fprintf(htmlfile, "<BODY>\n<CENTER><B><H1>AGI Commands</H1></B></CENTER>\n\n");
1329
1330
1331         fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
1332
1333         for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1334                 char *stringp=NULL;
1335                 e = &commands[x]; 
1336                 if (e)
1337                         join(fullcmd, sizeof(fullcmd), e->cmda);
1338                 /* Hide commands that start with '_' */
1339                 if (fullcmd[0] == '_')
1340                         continue;
1341
1342                 fprintf(htmlfile, "<TR><TD><TABLE BORDER=\"1\" CELLPADDING=\"5\" WIDTH=\"100%%\">\n");
1343                 fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TD></TR>\n", fullcmd,e->summary);
1344
1345
1346                 stringp=e->usage;
1347                 tempstr = strsep(&stringp, "\n");
1348
1349                 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">%s</TD></TR>\n", tempstr);
1350                 
1351                 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
1352                 while ((tempstr = strsep(&stringp, "\n")) != NULL) {
1353                 fprintf(htmlfile, "%s<BR>\n",tempstr);
1354
1355                 }
1356                 fprintf(htmlfile, "</TD></TR>\n");
1357                 fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
1358
1359         }
1360
1361         fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
1362         fclose(htmlfile);
1363         ast_cli(fd, "AGI HTML Commands Dumped to: %s\n", argv[2]);
1364         return RESULT_SUCCESS;
1365 }
1366
1367 static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced)
1368 {
1369         int res=0;
1370         struct localuser *u;
1371         char *args,*ringy;
1372         char tmp[256];
1373         int fds[2];
1374         int efd = -1;
1375         int pid;
1376         char *stringp=tmp;
1377         AGI agi;
1378         if (!data || !strlen(data)) {
1379                 ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
1380                 return -1;
1381         }
1382
1383
1384         memset(&agi, 0, sizeof(agi));
1385         strncpy(tmp, data, sizeof(tmp)-1);
1386         strsep(&stringp, "|");
1387         args = strsep(&stringp, "|");
1388         ringy = strsep(&stringp,"|");
1389         if (!args)
1390                 args = "";
1391         LOCAL_USER_ADD(u);
1392 #if 0
1393          /* Answer if need be */
1394         if (chan->_state != AST_STATE_UP) {
1395                 if (ringy) { /* if for ringing first */
1396                         /* a little ringy-dingy first */
1397                         ast_indicate(chan, AST_CONTROL_RINGING);  
1398                         sleep(3); 
1399                 }
1400                 if (ast_answer(chan)) {
1401                         LOCAL_USER_REMOVE(u);
1402                         return -1;
1403                 }
1404         }
1405 #endif
1406         res = launch_script(tmp, args, fds, enhanced ? &efd : NULL, &pid);
1407         if (!res) {
1408                 agi.fd = fds[1];
1409                 agi.ctrl = fds[0];
1410                 agi.audio = efd;
1411                 res = run_agi(chan, tmp, &agi, pid);
1412                 close(fds[0]);
1413                 close(fds[1]);
1414                 if (efd > -1)
1415                         close(efd);
1416         }
1417         LOCAL_USER_REMOVE(u);
1418         return res;
1419 }
1420
1421 static int agi_exec(struct ast_channel *chan, void *data)
1422 {
1423         return agi_exec_full(chan, data, 0);
1424 }
1425
1426 static int eagi_exec(struct ast_channel *chan, void *data)
1427 {
1428         int readformat;
1429         int res;
1430         readformat = chan->readformat;
1431         if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
1432                 ast_log(LOG_WARNING, "Unable to set channel '%s' to linear mode\n", chan->name);
1433                 return -1;
1434         }
1435         res = agi_exec_full(chan, data, 1);
1436         if (!res) {
1437                 if (ast_set_read_format(chan, readformat)) {
1438                         ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %s\n", chan->name, ast_getformatname(readformat));
1439                 }
1440         }
1441         return res;
1442 }
1443
1444 static char showagi_help[] =
1445 "Usage: show agi [topic]\n"
1446 "       When called with a topic as an argument, displays usage\n"
1447 "       information on the given command.  If called without a\n"
1448 "       topic, it provides a list of AGI commands.\n";
1449
1450
1451 static char dumpagihtml_help[] =
1452 "Usage: dump agihtml <filename>\n"
1453 "       Dumps the agi command list in html format to given filename\n";
1454
1455 static struct ast_cli_entry showagi = 
1456 { { "show", "agi", NULL }, handle_showagi, "Show AGI commands or specific help", showagi_help };
1457
1458 static struct ast_cli_entry dumpagihtml = 
1459 { { "dump", "agihtml", NULL }, handle_dumpagihtml, "Dumps a list of agi command in html format", dumpagihtml_help };
1460
1461 int unload_module(void)
1462 {
1463         STANDARD_HANGUP_LOCALUSERS;
1464         ast_cli_unregister(&showagi);
1465         ast_cli_unregister(&dumpagihtml);
1466         ast_unregister_application(eapp);
1467         return ast_unregister_application(app);
1468 }
1469
1470 int load_module(void)
1471 {
1472         ast_cli_register(&showagi);
1473         ast_cli_register(&dumpagihtml);
1474         ast_register_application(eapp, eagi_exec, synopsis, descrip);
1475         return ast_register_application(app, agi_exec, synopsis, descrip);
1476 }
1477
1478 char *description(void)
1479 {
1480         return tdesc;
1481 }
1482
1483 int usecount(void)
1484 {
1485         int res;
1486         STANDARD_USECOUNT(res);
1487         return res;
1488 }
1489
1490 char *key()
1491 {
1492         return ASTERISK_GPL_KEY;
1493 }
1494