Minor AGI patch
[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 <sys/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, 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 : "");
187         fdprintf(fd, "agi_dnid: %s\n", chan->dnid ? chan->dnid : "");
188         fdprintf(fd, "agi_rdnis: %s\n", chan->rdnis ? chan->rdnis : "");
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
406                 fdprintf(agi->fd, "200 result=%s\n", data);
407         if (res >= 0)
408                 return RESULT_SUCCESS;
409         else
410                 return RESULT_FAILURE;
411 }
412
413 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
414 {
415
416         if (argc != 3)
417                 return RESULT_SHOWUSAGE;
418         strncpy(chan->context, argv[2], sizeof(chan->context)-1);
419         fdprintf(agi->fd, "200 result=0\n");
420         return RESULT_SUCCESS;
421 }
422         
423 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, char **argv)
424 {
425         if (argc != 3)
426                 return RESULT_SHOWUSAGE;
427         strncpy(chan->exten, argv[2], sizeof(chan->exten)-1);
428         fdprintf(agi->fd, "200 result=0\n");
429         return RESULT_SUCCESS;
430 }
431
432 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char **argv)
433 {
434         int pri;
435         if (argc != 3)
436                 return RESULT_SHOWUSAGE;        
437         if (sscanf(argv[2], "%i", &pri) != 1)
438                 return RESULT_SHOWUSAGE;
439         chan->priority = pri - 1;
440         fdprintf(agi->fd, "200 result=0\n");
441         return RESULT_SUCCESS;
442 }
443                 
444 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
445 {
446         struct ast_filestream *fs;
447         struct ast_frame *f;
448         struct timeval tv, start;
449         long sample_offset = 0;
450         int res = 0;
451         int ms;
452
453         struct ast_dsp *sildet;         /* silence detector dsp */
454         int totalsilence = 0;
455         int dspsilence = 0;
456         int silence = 0;                /* amount of silence to allow */
457         int gotsilence = 0;             /* did we timeout for silence? */
458         char *silencestr;
459         int rfmt;
460
461
462         /* XXX EAGI FIXME XXX */
463
464         if (argc < 6)
465                 return RESULT_SHOWUSAGE;
466         if (sscanf(argv[5], "%i", &ms) != 1)
467                 return RESULT_SHOWUSAGE;
468
469         if (argc > 6)
470                 silencestr = strchr(argv[6],'s');
471         if ((argc > 7) && (!silencestr))
472                 silencestr = strchr(argv[7],'s');
473         if ((argc > 8) && (!silencestr))
474                 silencestr = strchr(argv[8],'s');
475
476         if (silencestr) {
477                 if (strlen(silencestr) > 2) {
478                         if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
479                                 silencestr++;
480                                 silencestr++;
481                                 if (silencestr)
482                                         silence = atoi(silencestr);
483                                 if (silence > 0)
484                                         silence *= 1000;
485                         }
486                 }
487         }
488
489         if (silence > 0) {
490                 rfmt = chan->readformat;
491                 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
492                 if (res < 0) {
493                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
494                         return -1;
495                 }
496                 sildet = ast_dsp_new();
497                 if (!sildet) {
498                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
499                         return -1;
500                 }
501                 ast_dsp_set_threshold(sildet, 256);
502         }
503
504         /* backward compatibility, if no offset given, arg[6] would have been
505          * caught below and taken to be a beep, else if it is a digit then it is a
506          * offset */
507         if ((argc >6) && (sscanf(argv[6], "%ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
508                 res = ast_streamfile(chan, "beep", chan->language);
509
510         if ((argc > 7) && (!strchr(argv[7], '=')))
511                 res = ast_streamfile(chan, "beep", chan->language);
512
513         if (!res)
514                 res = ast_waitstream(chan, argv[4]);
515         if (!res) {
516                 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY, 0, 0644);
517                 if (!fs) {
518                         res = -1;
519                         fdprintf(agi->fd, "200 result=%d (writefile)\n", res);
520                         return RESULT_FAILURE;
521                 }
522                 
523                 chan->stream = fs;
524                 ast_applystream(chan,fs);
525                 /* really should have checks */
526                 ast_seekstream(fs, sample_offset, SEEK_SET);
527                 ast_truncstream(fs);
528                 
529                 gettimeofday(&start, NULL);
530                 gettimeofday(&tv, NULL);
531                 while ((ms < 0) || (((tv.tv_sec - start.tv_sec) * 1000 + (tv.tv_usec - start.tv_usec)/1000) < ms)) {
532                         res = ast_waitfor(chan, -1);
533                         if (res < 0) {
534                                 ast_closestream(fs);
535                                 fdprintf(agi->fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
536                                 return RESULT_FAILURE;
537                         }
538                         f = ast_read(chan);
539                         if (!f) {
540                                 fdprintf(agi->fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
541                                 ast_closestream(fs);
542                                 return RESULT_FAILURE;
543                         }
544                         switch(f->frametype) {
545                         case AST_FRAME_DTMF:
546                                 if (strchr(argv[4], f->subclass)) {
547                                         /* This is an interrupting chracter */
548                                         sample_offset = ast_tellstream(fs);
549                                         fdprintf(agi->fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
550                                         ast_closestream(fs);
551                                         ast_frfree(f);
552                                         return RESULT_SUCCESS;
553                                 }
554                                 break;
555                         case AST_FRAME_VOICE:
556                                 ast_writestream(fs, f);
557                                 /* this is a safe place to check progress since we know that fs
558                                  * is valid after a write, and it will then have our current
559                                  * location */
560                                 sample_offset = ast_tellstream(fs);
561                                 if (silence > 0) {
562                                         dspsilence = 0;
563                                         ast_dsp_silence(sildet, f, &dspsilence);
564                                         if (dspsilence) {
565                                                 totalsilence = dspsilence;
566                                         } else {
567                                                 totalsilence = 0;
568                                         }
569                                         if (totalsilence > silence) {
570                                              /* Ended happily with silence */
571                                                 ast_frfree(f);
572                                                 gotsilence = 1;
573                                                 break;
574                                         }
575                                 }
576                                 break;
577                         }
578                         ast_frfree(f);
579                         gettimeofday(&tv, NULL);
580                         if (gotsilence)
581                                 break;
582         }
583
584                 if (gotsilence) {
585                         ast_stream_rewind(fs, silence-1000);
586                         ast_truncstream(fs);
587                 }               
588                 fdprintf(agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
589                 ast_closestream(fs);
590         } else
591                 fdprintf(agi->fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
592
593         if (silence > 0) {
594                 res = ast_set_read_format(chan, rfmt);
595                 if (res)
596                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
597                 ast_dsp_free(sildet);
598         }
599         return RESULT_SUCCESS;
600 }
601
602 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
603 {
604         int timeout;
605
606         if (argc != 3)
607                 return RESULT_SHOWUSAGE;
608         if (sscanf(argv[2], "%d", &timeout) != 1)
609                 return RESULT_SHOWUSAGE;
610         if (timeout < 0)
611                 timeout = 0;
612         if (timeout)
613                 chan->whentohangup = time(NULL) + timeout;
614         else
615                 chan->whentohangup = 0;
616         fdprintf(agi->fd, "200 result=0\n");
617         return RESULT_SUCCESS;
618 }
619
620 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **argv)
621 {
622         struct ast_channel *c;
623         if (argc==1) {
624             /* no argument: hangup the current channel */
625             ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
626             fdprintf(agi->fd, "200 result=1\n");
627             return RESULT_SUCCESS;
628         } else if (argc==2) {
629             /* one argument: look for info on the specified channel */
630             c = ast_channel_walk(NULL);
631             while (c) {
632                 if (strcasecmp(argv[1],c->name)==0) {
633                     /* we have a matching channel */
634                     ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
635                     fdprintf(agi->fd, "200 result=1\n");
636                     return RESULT_SUCCESS;
637                 }
638                 c = ast_channel_walk(c);
639             }
640             /* if we get this far no channel name matched the argument given */
641             fdprintf(agi->fd, "200 result=-1\n");
642             return RESULT_SUCCESS;
643         } else {
644             return RESULT_SHOWUSAGE;
645         }
646 }
647
648 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, char **argv)
649 {
650         int res;
651         struct ast_app *app;
652
653         if (argc < 2)
654                 return RESULT_SHOWUSAGE;
655
656         if (option_verbose > 2)
657                 ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
658
659         app = pbx_findapp(argv[1]);
660
661         if (app) {
662                 res = pbx_exec(chan, app, argv[2], 1);
663         } else {
664                 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
665                 res = -2;
666         }
667         fdprintf(agi->fd, "200 result=%d\n", res);
668
669         return res;
670 }
671
672 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, char **argv)
673 {
674         if (argv[2])
675                 ast_set_callerid(chan, argv[2], 0);
676
677 /*      strncpy(chan->callerid, argv[2], sizeof(chan->callerid)-1);
678 */      fdprintf(agi->fd, "200 result=1\n");
679         return RESULT_SUCCESS;
680 }
681
682 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, char **argv)
683 {
684         struct ast_channel *c;
685         if (argc==2) {
686             /* no argument: supply info on the current channel */
687             fdprintf(agi->fd, "200 result=%d\n", chan->_state);
688             return RESULT_SUCCESS;
689         } else if (argc==3) {
690             /* one argument: look for info on the specified channel */
691             c = ast_channel_walk(NULL);
692             while (c) {
693                 if (strcasecmp(argv[2],c->name)==0) {
694                     fdprintf(agi->fd, "200 result=%d\n", c->_state);
695                     return RESULT_SUCCESS;
696                 }
697                 c = ast_channel_walk(c);
698             }
699             /* if we get this far no channel name matched the argument given */
700             fdprintf(agi->fd, "200 result=-1\n");
701             return RESULT_SUCCESS;
702         } else {
703             return RESULT_SHOWUSAGE;
704         }
705 }
706
707 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
708 {
709         if (argv[3])
710                 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
711
712         fdprintf(agi->fd, "200 result=1\n");
713         return RESULT_SUCCESS;
714 }
715
716 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
717 {
718         char *tempstr;
719
720         if ((tempstr = pbx_builtin_getvar_helper(chan, argv[2])) ) 
721                         fdprintf(agi->fd, "200 result=1 (%s)\n", tempstr);
722         else
723                         fdprintf(agi->fd, "200 result=0\n");
724
725         return RESULT_SUCCESS;
726 }
727
728 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **argv)
729 {
730         int level = 0;
731         char *prefix;
732
733         if (argc < 2)
734                 return RESULT_SHOWUSAGE;
735
736         if (argv[2])
737                 sscanf(argv[2], "%d", &level);
738
739         switch (level) {
740                 case 4:
741                         prefix = VERBOSE_PREFIX_4;
742                         break;
743                 case 3:
744                         prefix = VERBOSE_PREFIX_3;
745                         break;
746                 case 2:
747                         prefix = VERBOSE_PREFIX_2;
748                         break;
749                 case 1:
750                 default:
751                         prefix = VERBOSE_PREFIX_1;
752                         break;
753         }
754
755         if (level <= option_verbose)
756                 ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
757         
758         fdprintf(agi->fd, "200 result=1\n");
759         
760         return RESULT_SUCCESS;
761 }
762
763 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, char **argv)
764 {
765         int res;
766         char tmp[256];
767         if (argc != 4)
768                 return RESULT_SHOWUSAGE;
769         res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
770         if (res) 
771                         fdprintf(agi->fd, "200 result=0\n");
772         else
773                         fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
774
775         return RESULT_SUCCESS;
776 }
777
778 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, char **argv)
779 {
780         int res;
781         if (argc != 5)
782                 return RESULT_SHOWUSAGE;
783         res = ast_db_put(argv[2], argv[3], argv[4]);
784         if (res) 
785                         fdprintf(agi->fd, "200 result=0\n");
786         else
787                         fdprintf(agi->fd, "200 result=1\n");
788
789         return RESULT_SUCCESS;
790 }
791
792 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, char **argv)
793 {
794         int res;
795         if (argc != 4)
796                 return RESULT_SHOWUSAGE;
797         res = ast_db_del(argv[2], argv[3]);
798         if (res) 
799                 fdprintf(agi->fd, "200 result=0\n");
800         else
801                 fdprintf(agi->fd, "200 result=1\n");
802
803         return RESULT_SUCCESS;
804 }
805
806 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char **argv)
807 {
808         int res;
809         if ((argc < 3) || (argc > 4))
810                 return RESULT_SHOWUSAGE;
811         if (argc == 4)
812                 res = ast_db_deltree(argv[2], argv[3]);
813         else
814                 res = ast_db_deltree(argv[2], NULL);
815
816         if (res) 
817                 fdprintf(agi->fd, "200 result=0\n");
818         else
819                 fdprintf(agi->fd, "200 result=1\n");
820         return RESULT_SUCCESS;
821 }
822
823 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
824 {
825         fdprintf(agi->fd, "200 result=0\n");
826         return RESULT_SUCCESS;
827 }
828
829 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
830 {
831         if (!strncasecmp(argv[2],"on",2)) {
832                 if (argc > 3)
833                         ast_moh_start(chan, argv[3]);
834                 else
835                         ast_moh_start(chan, NULL);
836         }
837         if (!strncasecmp(argv[2],"off",3)) {
838                 ast_moh_stop(chan);
839         }
840         fdprintf(agi->fd, "200 result=0\n");
841         return RESULT_SUCCESS;
842 }
843
844 static char usage_setmusic[] =
845 " Usage: SET MUSIC ON <on|off> <class>\n"
846 "       Enables/Disables the music on hold generator.  If <class> is\n"
847 " not specified then the default music on hold class will be used.\n"
848 " Always returns 0\n";
849
850 static char usage_dbput[] =
851 " Usage: DATABASE PUT <family> <key> <value>\n"
852 "       Adds or updates an entry in the Asterisk database for a\n"
853 " given family, key, and value.\n"
854 " Returns 1 if succesful, 0 otherwise\n";
855
856 static char usage_dbget[] =
857 " Usage: DATABASE GET <family> <key>\n"
858 "       Retrieves an entry in the Asterisk database for a\n"
859 " given family and key.\n"
860 "       Returns 0 if <key> is not set.  Returns 1 if <key>\n"
861 " is set and returns the variable in parenthesis\n"
862 " example return code: 200 result=1 (testvariable)\n";
863
864 static char usage_dbdel[] =
865 " Usage: DATABASE DEL <family> <key>\n"
866 "       Deletes an entry in the Asterisk database for a\n"
867 " given family and key.\n"
868 " Returns 1 if succesful, 0 otherwise\n";
869
870 static char usage_dbdeltree[] =
871 " Usage: DATABASE DELTREE <family> [keytree]\n"
872 "       Deletes a family or specific keytree withing a family\n"
873 " in the Asterisk database.\n"
874 " Returns 1 if succesful, 0 otherwise\n";
875
876 static char usage_verbose[] =
877 " Usage: VERBOSE <message> <level>\n"
878 "       Sends <message> to the console via verbose message system.\n"
879 "       <level> is the the verbose level (1-4)\n"
880 "       Always returns 1\n";
881
882 static char usage_getvariable[] =
883 " Usage: GET VARIABLE <variablename>\n"
884 "       Returns 0 if <variablename> is not set.  Returns 1 if <variablename>\n"
885 " is set and returns the variable in parenthesis\n"
886 " example return code: 200 result=1 (testvariable)\n";
887
888 static char usage_setvariable[] =
889 " Usage: SET VARIABLE <variablename> <value>\n";
890
891 static char usage_channelstatus[] =
892 " Usage: CHANNEL STATUS [<channelname>]\n"
893 "       Returns the status of the specified channel.\n" 
894 "       If no channel name is given the returns the status of the\n"
895 "       current channel.\n"
896 "       Return values:\n"
897 " 0 Channel is down and available\n"
898 " 1 Channel is down, but reserved\n"
899 " 2 Channel is off hook\n"
900 " 3 Digits (or equivalent) have been dialed\n"
901 " 4 Line is ringing\n"
902 " 5 Remote end is ringing\n"
903 " 6 Line is up\n"
904 " 7 Line is busy\n";
905
906 static char usage_setcallerid[] =
907 " Usage: SET CALLERID <number>\n"
908 "       Changes the callerid of the current channel.\n";
909
910 static char usage_exec[] =
911 " Usage: EXEC <application> <options>\n"
912 "       Executes <application> with given <options>.\n"
913 "       Returns whatever the application returns, or -2 on failure to find application\n";
914
915 static char usage_hangup[] =
916 " Usage: HANGUP [<channelname>]\n"
917 "       Hangs up the specified channel.\n"
918 "       If no channel name is given, hangs up the current channel\n";
919
920 static char usage_answer[] = 
921 " Usage: ANSWER\n"
922 "        Answers channel if not already in answer state. Returns -1 on\n"
923 " channel failure, or 0 if successful.\n";
924
925 static char usage_waitfordigit[] = 
926 " Usage: WAIT FOR DIGIT <timeout>\n"
927 "        Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
928 " Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
929 " the numerical value of the ascii of the digit if one is received.  Use -1\n"
930 " for the timeout value if you desire the call to block indefinitely.\n";
931
932 static char usage_sendtext[] =
933 " Usage: SEND TEXT \"<text to send>\"\n"
934 "        Sends the given text on a channel.  Most channels do not support the\n"
935 " transmission of text.  Returns 0 if text is sent, or if the channel does not\n"
936 " support text transmission.  Returns -1 only on error/hangup.  Text\n"
937 " consisting of greater than one word should be placed in quotes since the\n"
938 " command only accepts a single argument.\n";
939
940 static char usage_recvchar[] =
941 " Usage: RECEIVE CHAR <timeout>\n"
942 "        Receives a character of text on a channel.  Specify timeout to be the\n"
943 " maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
944 " do not support the reception of text.  Returns the decimal value of the character\n"
945 " if one is received, or 0 if the channel does not support text reception.  Returns\n"
946 " -1 only on error/hangup.\n";
947
948 static char usage_tddmode[] =
949 " Usage: TDD MODE <on|off>\n"
950 "        Enable/Disable TDD transmission/reception on a channel. Returns 1 if\n"
951 " successful, or 0 if channel is not TDD-capable.\n";
952
953 static char usage_sendimage[] =
954 " Usage: SEND IMAGE <image>\n"
955 "        Sends the given image on a channel.  Most channels do not support the\n"
956 " transmission of images.  Returns 0 if image is sent, or if the channel does not\n"
957 " support image transmission.  Returns -1 only on error/hangup.  Image names\n"
958 " should not include extensions.\n";
959
960 static char usage_streamfile[] =
961 " Usage: STREAM FILE <filename> <escape digits> [sample offset]\n"
962 "        Send the given file, allowing playback to be interrupted by the given\n"
963 " digits, if any.  Use double quotes for the digits if you wish none to be\n"
964 " permitted.  If sample offset is provided then the audio will seek to sample\n"
965 " offset before play starts.  Returns 0 if playback completes without a digit\n"
966 " being pressed, or the ASCII numerical value of the digit if one was pressed,\n"
967 " or -1 on error or if the channel was disconnected.  Remember, the file\n"
968 " extension must not be included in the filename.\n";
969
970 static char usage_saynumber[] =
971 " Usage: SAY NUMBER <number> <escape digits>\n"
972 "        Say a given number, returning early if any of the given DTMF digits\n"
973 " are received on the channel.  Returns 0 if playback completes without a digit\n"
974 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
975 " -1 on error/hangup.\n";
976
977 static char usage_saydigits[] =
978 " Usage: SAY DIGITS <number> <escape digits>\n"
979 "        Say a given digit string, returning early if any of the given DTMF digits\n"
980 " are received on the channel.  Returns 0 if playback completes without a digit\n"
981 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
982 " -1 on error/hangup.\n";
983
984 static char usage_getdata[] =
985 " Usage: GET DATA <file to be streamed> [timeout] [max digits]\n"
986 "        Stream the given file, and recieve DTMF data. Returns the digits recieved\n"
987 "from the channel at the other end.\n";
988
989 static char usage_setcontext[] =
990 " Usage: SET CONTEXT <desired context>\n"
991 "        Sets the context for continuation upon exiting the application.\n";
992
993 static char usage_setextension[] =
994 " Usage: SET EXTENSION <new extension>\n"
995 "        Changes the extension for continuation upon exiting the application.\n";
996
997 static char usage_setpriority[] =
998 " Usage: SET PRIORITY <num>\n"
999 "        Changes the priority for continuation upon exiting the application.\n";
1000
1001 static char usage_recordfile[] =
1002 " Usage: RECORD FILE <filename> <format> <escape digits> <timeout> [offset samples] [BEEP] [s=silence]\n"
1003 "        Record to a file until a given dtmf digit in the sequence is received\n"
1004 " Returns -1 on hangup or error.  The format will specify what kind of file\n"
1005 " will be recorded.  The timeout is the maximum record time in milliseconds, or\n"
1006 " -1 for no timeout. Offset samples is optional, and if provided will seek to\n"
1007 " the offset without exceeding the end of the file.  \"silence\" is the number\n"
1008 " of seconds of silence allowed before the function returns despite the\n"
1009 " lack of dtmf digits or reaching timeout.  Silence value must be\n"
1010 " preceeded by \"s=\" and is optional.\n";
1011
1012
1013 static char usage_autohangup[] =
1014 " Usage: SET AUTOHANGUP <time>\n"
1015 "    Cause the channel to automatically hangup at <time> seconds in the\n"
1016 "future.  Of course it can be hungup before then as well.   Setting to\n"
1017 "0 will cause the autohangup feature to be disabled on this channel.\n";
1018
1019 static char usage_noop[] =
1020 " Usage: NOOP\n"
1021 "    Does nothing.\n";
1022
1023 static agi_command commands[] = {
1024         { { "answer", NULL }, handle_answer, "Asserts answer", usage_answer },
1025         { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
1026         { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
1027         { { "receive", "char", NULL }, handle_recvchar, "Receives text from channels supporting it", usage_recvchar },
1028         { { "tdd", "mode", NULL }, handle_tddmode, "Sends text to channels supporting it", usage_tddmode },
1029         { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
1030         { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
1031         { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
1032         { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
1033         { { "get", "data", NULL }, handle_getdata, "Gets data on a channel", usage_getdata },
1034         { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
1035         { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
1036         { { "set", "priority", NULL }, handle_setpriority, "Prioritizes the channel", usage_setpriority },
1037         { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
1038         { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
1039         { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
1040         { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
1041         { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
1042         { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus },
1043         { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable },
1044         { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable },
1045         { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose },
1046         { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget },
1047         { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput },
1048         { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel },
1049         { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree },
1050         { { "noop", NULL }, handle_noop, "Does nothing", usage_noop },
1051         { { "set", "music", NULL }, handle_setmusic, "Enable/Disable Music on hold generator", usage_setmusic }
1052 };
1053
1054 static void join(char *s, int len, char *w[])
1055 {
1056         int x;
1057         /* Join words into a string */
1058         strcpy(s, "");
1059         for (x=0;w[x];x++) {
1060                 if (x)
1061                         strncat(s, " ", len - strlen(s));
1062                 strncat(s, w[x], len - strlen(s));
1063         }
1064 }
1065
1066 static int help_workhorse(int fd, char *match[])
1067 {
1068         char fullcmd[80];
1069         char matchstr[80];
1070         int x;
1071         struct agi_command *e;
1072         if (match)
1073                 join(matchstr, sizeof(matchstr), match);
1074         for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1075                 e = &commands[x]; 
1076                 if (e)
1077                         join(fullcmd, sizeof(fullcmd), e->cmda);
1078                 /* Hide commands that start with '_' */
1079                 if (fullcmd[0] == '_')
1080                         continue;
1081                 if (match) {
1082                         if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1083                                 continue;
1084                         }
1085                 }
1086                 ast_cli(fd, "%20.20s   %s\n", fullcmd, e->summary);
1087         }
1088         return 0;
1089 }
1090
1091 static agi_command *find_command(char *cmds[], int exact)
1092 {
1093         int x;
1094         int y;
1095         int match;
1096         for (x=0;x < sizeof(commands) / sizeof(commands[0]);x++) {
1097                 /* start optimistic */
1098                 match = 1;
1099                 for (y=0;match && cmds[y]; y++) {
1100                         /* If there are no more words in the command (and we're looking for
1101                            an exact match) or there is a difference between the two words,
1102                            then this is not a match */
1103                         if (!commands[x].cmda[y] && !exact)
1104                                 break;
1105                         /* don't segfault if the next part of a command doesn't exist */
1106                         if (!commands[x].cmda[y]) return NULL;
1107                         if (strcasecmp(commands[x].cmda[y], cmds[y]))
1108                                 match = 0;
1109                 }
1110                 /* If more words are needed to complete the command then this is not
1111                    a candidate (unless we're looking for a really inexact answer  */
1112                 if ((exact > -1) && commands[x].cmda[y])
1113                         match = 0;
1114                 if (match)
1115                         return &commands[x];
1116         }
1117         return NULL;
1118 }
1119
1120
1121 static int parse_args(char *s, int *max, char *argv[])
1122 {
1123         int x=0;
1124         int quoted=0;
1125         int escaped=0;
1126         int whitespace=1;
1127         char *cur;
1128
1129         cur = s;
1130         while(*s) {
1131                 switch(*s) {
1132                 case '"':
1133                         /* If it's escaped, put a literal quote */
1134                         if (escaped) 
1135                                 goto normal;
1136                         else 
1137                                 quoted = !quoted;
1138                         if (quoted && whitespace) {
1139                                 /* If we're starting a quote, coming off white space start a new word, too */
1140                                 argv[x++] = cur;
1141                                 whitespace=0;
1142                         }
1143                         escaped = 0;
1144                 break;
1145                 case ' ':
1146                 case '\t':
1147                         if (!quoted && !escaped) {
1148                                 /* If we're not quoted, mark this as whitespace, and
1149                                    end the previous argument */
1150                                 whitespace = 1;
1151                                 *(cur++) = '\0';
1152                         } else
1153                                 /* Otherwise, just treat it as anything else */ 
1154                                 goto normal;
1155                         break;
1156                 case '\\':
1157                         /* If we're escaped, print a literal, otherwise enable escaping */
1158                         if (escaped) {
1159                                 goto normal;
1160                         } else {
1161                                 escaped=1;
1162                         }
1163                         break;
1164                 default:
1165 normal:
1166                         if (whitespace) {
1167                                 if (x >= MAX_ARGS -1) {
1168                                         ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1169                                         break;
1170                                 }
1171                                 /* Coming off of whitespace, start the next argument */
1172                                 argv[x++] = cur;
1173                                 whitespace=0;
1174                         }
1175                         *(cur++) = *s;
1176                         escaped=0;
1177                 }
1178                 s++;
1179         }
1180         /* Null terminate */
1181         *(cur++) = '\0';
1182         argv[x] = NULL;
1183         *max = x;
1184         return 0;
1185 }
1186
1187 static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf)
1188 {
1189         char *argv[MAX_ARGS];
1190         int argc = 0;
1191         int res;
1192         agi_command *c;
1193         argc = MAX_ARGS;
1194         parse_args(buf, &argc, argv);
1195 #if     0
1196         { int x;
1197         for (x=0;x<argc;x++) 
1198                 fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
1199 #endif
1200         c = find_command(argv, 0);
1201         if (c) {
1202                 res = c->handler(chan, agi, argc, argv);
1203                 switch(res) {
1204                 case RESULT_SHOWUSAGE:
1205                         fdprintf(agi->fd, "520-Invalid command syntax.  Proper usage follows:\n");
1206                         fdprintf(agi->fd, c->usage);
1207                         fdprintf(agi->fd, "520 End of proper usage.\n");
1208                         break;
1209                 case RESULT_FAILURE:
1210                         /* They've already given the failure.  We've been hung up on so handle this
1211                            appropriately */
1212                         return -1;
1213                 }
1214         } else {
1215                 fdprintf(agi->fd, "510 Invalid or unknown command\n");
1216         }
1217         return 0;
1218 }
1219
1220 static int run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid)
1221 {
1222         struct ast_channel *c;
1223         int outfd;
1224         int ms;
1225         int returnstatus = 0;
1226         struct ast_frame *f;
1227         char buf[2048];
1228         FILE *readf;
1229         if (!(readf = fdopen(agi->ctrl, "r"))) {
1230                 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
1231                 kill(pid, SIGHUP);
1232                 return -1;
1233         }
1234         setlinebuf(readf);
1235         setup_env(chan, request, agi->fd, (agi->audio > -1));
1236         for (;;) {
1237                 ms = -1;
1238                 c = ast_waitfor_nandfds(&chan, 1, &agi->ctrl, 1, NULL, &outfd, &ms);
1239                 if (c) {
1240                         /* Idle the channel until we get a command */
1241                         f = ast_read(c);
1242                         if (!f) {
1243                                 ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
1244                                 returnstatus = -1;
1245                                 break;
1246                         } else {
1247                                 /* If it's voice, write it to the audio pipe */
1248                                 if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
1249                                         /* Write, ignoring errors */
1250                                         write(agi->audio, f->data, f->datalen);
1251                                 }
1252                                 ast_frfree(f);
1253                         }
1254                 } else if (outfd > -1) {
1255                         if (!fgets(buf, sizeof(buf), readf)) {
1256                                 /* Program terminated */
1257                                 if (returnstatus)
1258                                         returnstatus = -1;
1259                                 if (option_verbose > 2) 
1260                                         ast_verbose(VERBOSE_PREFIX_3 "AGI Script %s completed, returning %d\n", request, returnstatus);
1261                                 /* No need to kill the pid anymore, since they closed us */
1262                                 pid = -1;
1263                                 break;
1264                         }
1265                           /* get rid of trailing newline, if any */
1266                         if (*buf && buf[strlen(buf) - 1] == '\n')
1267                                 buf[strlen(buf) - 1] = 0;
1268
1269                         returnstatus |= agi_handle_command(chan, agi, buf);
1270                         /* If the handle_command returns -1, we need to stop */
1271                         if (returnstatus < 0) {
1272                                 break;
1273                         }
1274                 } else {
1275                         ast_log(LOG_WARNING, "No channel, no fd?\n");
1276                         returnstatus = -1;
1277                         break;
1278                 }
1279         }
1280         /* Notify process */
1281         if (pid > -1)
1282                 kill(pid, SIGHUP);
1283         fclose(readf);
1284         return returnstatus;
1285 }
1286
1287 static int handle_showagi(int fd, int argc, char *argv[]) {
1288         struct agi_command *e;
1289         char fullcmd[80];
1290         if ((argc < 2))
1291                 return RESULT_SHOWUSAGE;
1292         if (argc > 2) {
1293                 e = find_command(argv + 2, 1);
1294                 if (e) 
1295                         ast_cli(fd, e->usage);
1296                 else {
1297                         if (find_command(argv + 2, -1)) {
1298                                 return help_workhorse(fd, argv + 1);
1299                         } else {
1300                                 join(fullcmd, sizeof(fullcmd), argv+1);
1301                                 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1302                         }
1303                 }
1304         } else {
1305                 return help_workhorse(fd, NULL);
1306         }
1307         return RESULT_SUCCESS;
1308 }
1309
1310 static int handle_dumpagihtml(int fd, int argc, char *argv[]) {
1311         struct agi_command *e;
1312         char fullcmd[80];
1313         char *tempstr;
1314         int x;
1315         FILE *htmlfile;
1316
1317         if ((argc < 3))
1318                 return RESULT_SHOWUSAGE;
1319
1320         if (!(htmlfile = fopen(argv[2], "wt"))) {
1321                 ast_cli(fd, "Could not create file '%s'\n", argv[2]);
1322                 return RESULT_SHOWUSAGE;
1323         }
1324
1325         fprintf(htmlfile, "<HTML>\n<HEAD>\n<TITLE>AGI Commands</TITLE>\n</HEAD>\n");
1326         fprintf(htmlfile, "<BODY>\n<CENTER><B><H1>AGI Commands</H1></B></CENTER>\n\n");
1327
1328
1329         fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
1330
1331         for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1332                 char *stringp=NULL;
1333                 e = &commands[x]; 
1334                 if (e)
1335                         join(fullcmd, sizeof(fullcmd), e->cmda);
1336                 /* Hide commands that start with '_' */
1337                 if (fullcmd[0] == '_')
1338                         continue;
1339
1340                 fprintf(htmlfile, "<TR><TD><TABLE BORDER=\"1\" CELLPADDING=\"5\" WIDTH=\"100%%\">\n");
1341                 fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TD></TR>\n", fullcmd,e->summary);
1342
1343
1344                 stringp=e->usage;
1345                 tempstr = strsep(&stringp, "\n");
1346
1347                 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">%s</TD></TR>\n", tempstr);
1348                 
1349                 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
1350                 while ((tempstr = strsep(&stringp, "\n")) != NULL) {
1351                 fprintf(htmlfile, "%s<BR>\n",tempstr);
1352
1353                 }
1354                 fprintf(htmlfile, "</TD></TR>\n");
1355                 fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
1356
1357         }
1358
1359         fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
1360         fclose(htmlfile);
1361         ast_cli(fd, "AGI HTML Commands Dumped to: %s\n", argv[2]);
1362         return RESULT_SUCCESS;
1363 }
1364
1365 static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced)
1366 {
1367         int res=0;
1368         struct localuser *u;
1369         char *args,*ringy;
1370         char tmp[256];
1371         int fds[2];
1372         int efd = -1;
1373         int pid;
1374         char *stringp=tmp;
1375         AGI agi;
1376         if (!data || !strlen(data)) {
1377                 ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
1378                 return -1;
1379         }
1380
1381
1382         memset(&agi, 0, sizeof(agi));
1383         strncpy(tmp, data, sizeof(tmp)-1);
1384         strsep(&stringp, "|");
1385         args = strsep(&stringp, "|");
1386         ringy = strsep(&stringp,"|");
1387         if (!args)
1388                 args = "";
1389         LOCAL_USER_ADD(u);
1390 #if 0
1391          /* Answer if need be */
1392         if (chan->_state != AST_STATE_UP) {
1393                 if (ringy) { /* if for ringing first */
1394                         /* a little ringy-dingy first */
1395                         ast_indicate(chan, AST_CONTROL_RINGING);  
1396                         sleep(3); 
1397                 }
1398                 if (ast_answer(chan)) {
1399                         LOCAL_USER_REMOVE(u);
1400                         return -1;
1401                 }
1402         }
1403 #endif
1404         res = launch_script(tmp, args, fds, enhanced ? &efd : NULL, &pid);
1405         if (!res) {
1406                 agi.fd = fds[1];
1407                 agi.ctrl = fds[0];
1408                 agi.audio = efd;
1409                 res = run_agi(chan, tmp, &agi, pid);
1410                 close(fds[0]);
1411                 close(fds[1]);
1412                 if (efd > -1)
1413                         close(efd);
1414         }
1415         LOCAL_USER_REMOVE(u);
1416         return res;
1417 }
1418
1419 static int agi_exec(struct ast_channel *chan, void *data)
1420 {
1421         return agi_exec_full(chan, data, 0);
1422 }
1423
1424 static int eagi_exec(struct ast_channel *chan, void *data)
1425 {
1426         int readformat;
1427         int res;
1428         readformat = chan->readformat;
1429         if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
1430                 ast_log(LOG_WARNING, "Unable to set channel '%s' to linear mode\n", chan->name);
1431                 return -1;
1432         }
1433         res = agi_exec_full(chan, data, 1);
1434         if (!res) {
1435                 if (ast_set_read_format(chan, readformat)) {
1436                         ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %d\n", chan->name, readformat);
1437                 }
1438         }
1439         return res;
1440 }
1441
1442 static char showagi_help[] =
1443 "Usage: show agi [topic]\n"
1444 "       When called with a topic as an argument, displays usage\n"
1445 "       information on the given command.  If called without a\n"
1446 "       topic, it provides a list of AGI commands.\n";
1447
1448
1449 static char dumpagihtml_help[] =
1450 "Usage: dump agihtml <filename>\n"
1451 "       Dumps the agi command list in html format to given filename\n";
1452
1453 static struct ast_cli_entry showagi = 
1454 { { "show", "agi", NULL }, handle_showagi, "Show AGI commands or specific help", showagi_help };
1455
1456 static struct ast_cli_entry dumpagihtml = 
1457 { { "dump", "agihtml", NULL }, handle_dumpagihtml, "Dumps a list of agi command in html format", dumpagihtml_help };
1458
1459 int unload_module(void)
1460 {
1461         STANDARD_HANGUP_LOCALUSERS;
1462         ast_cli_unregister(&showagi);
1463         ast_cli_unregister(&dumpagihtml);
1464         ast_unregister_application(eapp);
1465         return ast_unregister_application(app);
1466 }
1467
1468 int load_module(void)
1469 {
1470         ast_cli_register(&showagi);
1471         ast_cli_register(&dumpagihtml);
1472         ast_register_application(eapp, eagi_exec, synopsis, descrip);
1473         return ast_register_application(app, agi_exec, synopsis, descrip);
1474 }
1475
1476 char *description(void)
1477 {
1478         return tdesc;
1479 }
1480
1481 int usecount(void)
1482 {
1483         int res;
1484         STANDARD_USECOUNT(res);
1485         return res;
1486 }
1487
1488 char *key()
1489 {
1490         return ASTERISK_GPL_KEY;
1491 }
1492