2 * Asterisk -- A telephony toolkit for Linux.
4 * Asterisk Gateway Interface
6 * Copyright (C) 1999-2004, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
14 #include <sys/types.h>
16 #include <sys/socket.h>
17 #include <netinet/in.h>
18 #include <netinet/tcp.h>
19 #include <arpa/inet.h>
20 #include <asterisk/file.h>
21 #include <asterisk/logger.h>
22 #include <asterisk/channel.h>
23 #include <asterisk/pbx.h>
24 #include <asterisk/module.h>
25 #include <asterisk/astdb.h>
26 #include <asterisk/callerid.h>
37 #include <asterisk/cli.h>
38 #include <asterisk/logger.h>
39 #include <asterisk/options.h>
40 #include <asterisk/image.h>
41 #include <asterisk/say.h>
42 #include <asterisk/app.h>
43 #include <asterisk/dsp.h>
44 #include <asterisk/musiconhold.h>
45 #include <asterisk/manager.h>
46 #include <asterisk/utils.h>
47 #include <asterisk/lock.h>
48 #include <asterisk/agi.h>
49 #include "../asterisk.h"
50 #include "../astconf.h"
53 #define MAX_COMMANDS 128
55 /* Recycle some stuff from the CLI interface */
56 #define fdprintf agi_debug_cli
58 static char *tdesc = "Asterisk Gateway Interface (AGI)";
60 static char *app = "AGI";
62 static char *eapp = "EAGI";
64 static char *deadapp = "DeadAGI";
66 static char *synopsis = "Executes an AGI compliant application";
67 static char *esynopsis = "Executes an EAGI compliant application";
68 static char *deadsynopsis = "Executes AGI on a hungup channel";
70 static char *descrip =
71 " [E|Dead]AGI(command|args): Executes an Asterisk Gateway Interface compliant\n"
72 "program on a channel. AGI allows Asterisk to launch external programs\n"
73 "written in any language to control a telephony channel, play audio,\n"
74 "read DTMF digits, etc. by communicating with the AGI protocol on stdin\n"
76 "Returns -1 on hangup (except for DeadAGI) or if application requested\n"
77 " hangup, or 0 on non-hangup exit. \n"
78 "Using 'EAGI' provides enhanced AGI, with incoming audio available out of band"
79 "on file descriptor 3\n\n"
80 "Use the CLI command 'show agi' to list available agi commands\n";
82 static int agidebug = 0;
89 #define TONE_BLOCK_SIZE 200
91 /* Max time to connect to an AGI remote host */
92 #define MAX_AGI_CONNECT 2000
96 static void agi_debug_cli(int fd, char *fmt, ...)
103 res = vasprintf(&stuff, fmt, ap);
106 ast_log(LOG_ERROR, "Out of memory\n");
109 ast_verbose("AGI Tx >> %s", stuff);
110 ast_carefulwrite(fd, stuff, strlen(stuff), 100);
115 static int launch_netscript(char *agiurl, char *argv[], int *fds, int *efd, int *opid)
119 struct pollfd pfds[1];
121 char *c; int port = AGI_PORT;
123 struct sockaddr_in sin;
125 struct ast_hostent ahp;
126 ast_log(LOG_DEBUG, "Blah\n");
127 host = ast_strdupa(agiurl + 6);
130 /* Strip off any script name */
131 if ((c = strchr(host, '/'))) {
136 if ((c = strchr(host, ':'))) {
142 ast_log(LOG_WARNING, "AGI URI's don't support Enhanced AGI yet\n");
145 hp = ast_gethostbyname(host, &ahp);
147 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", host);
150 s = socket(AF_INET, SOCK_STREAM, 0);
152 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
155 flags = fcntl(s, F_GETFL);
157 ast_log(LOG_WARNING, "Fcntl(F_GETFL) failed: %s\n", strerror(errno));
161 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
162 ast_log(LOG_WARNING, "Fnctl(F_SETFL) failed: %s\n", strerror(errno));
166 memset(&sin, 0, sizeof(sin));
167 sin.sin_family = AF_INET;
168 sin.sin_port = htons(port);
169 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
170 if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) && (errno != EINPROGRESS)) {
171 ast_log(LOG_WARNING, "Connect failed with unexpected error: %s\n", strerror(errno));
176 pfds[0].events = POLLOUT;
177 if (poll(pfds, 1, MAX_AGI_CONNECT) != 1) {
178 ast_log(LOG_WARNING, "Connect to '%s' failed!\n", agiurl);
182 if (write(s, "agi_network: yes\n", strlen("agi_network: yes\n")) < 0) {
183 ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
187 ast_log(LOG_DEBUG, "Wow, connected!\n");
194 static int launch_script(char *script, char *argv[], int *fds, int *efd, int *opid)
204 if (!strncasecmp(script, "agi://", 6))
205 return launch_netscript(script, argv, fds, efd, opid);
207 if (script[0] != '/') {
208 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_AGI_DIR, script);
212 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
216 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
223 ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
230 res = fcntl(audio[1], F_GETFL);
232 res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
234 ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
246 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
250 /* Redirect stdin and out, provide enhanced audio channel if desired */
251 dup2(fromast[0], STDIN_FILENO);
252 dup2(toast[1], STDOUT_FILENO);
254 dup2(audio[0], STDERR_FILENO + 1);
256 close(STDERR_FILENO + 1);
258 /* Close everything but stdin/out/error */
259 for (x=STDERR_FILENO + 2;x<1024;x++)
263 /* Can't use ast_log since FD's are closed */
264 fprintf(stderr, "Failed to execute '%s': %s\n", script, strerror(errno));
267 if (option_verbose > 2)
268 ast_verbose(VERBOSE_PREFIX_3 "Launched AGI Script %s\n", script);
274 /* close what we're not using in the parent */
288 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced)
290 /* Print initial environment, with agi_request always being the first
292 fdprintf(fd, "agi_request: %s\n", request);
293 fdprintf(fd, "agi_channel: %s\n", chan->name);
294 fdprintf(fd, "agi_language: %s\n", chan->language);
295 fdprintf(fd, "agi_type: %s\n", chan->type);
296 fdprintf(fd, "agi_uniqueid: %s\n", chan->uniqueid);
299 fdprintf(fd, "agi_callerid: %s\n", chan->cid.cid_num ? chan->cid.cid_num : "unknown");
300 fdprintf(fd, "agi_calleridname: %s\n", chan->cid.cid_name ? chan->cid.cid_name : "unknown");
301 fdprintf(fd, "agi_dnid: %s\n", chan->cid.cid_dnid ? chan->cid.cid_dnid : "unknown");
302 fdprintf(fd, "agi_rdnis: %s\n", chan->cid.cid_rdnis ? chan->cid.cid_rdnis : "unknown");
304 /* Context information */
305 fdprintf(fd, "agi_context: %s\n", chan->context);
306 fdprintf(fd, "agi_extension: %s\n", chan->exten);
307 fdprintf(fd, "agi_priority: %d\n", chan->priority);
308 fdprintf(fd, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
310 /* User information */
311 fdprintf(fd, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
313 /* End with empty return */
317 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
321 if (chan->_state != AST_STATE_UP) {
322 /* Answer the chan */
323 res = ast_answer(chan);
325 fdprintf(agi->fd, "200 result=%d\n", res);
327 return RESULT_SUCCESS;
329 return RESULT_FAILURE;
332 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
337 return RESULT_SHOWUSAGE;
338 if (sscanf(argv[3], "%i", &to) != 1)
339 return RESULT_SHOWUSAGE;
340 res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
341 fdprintf(agi->fd, "200 result=%d\n", res);
343 return RESULT_SUCCESS;
345 return RESULT_FAILURE;
348 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
352 return RESULT_SHOWUSAGE;
353 /* At the moment, the parser (perhaps broken) returns with
354 the last argument PLUS the newline at the end of the input
355 buffer. This probably needs to be fixed, but I wont do that
356 because other stuff may break as a result. The right way
357 would probably be to strip off the trailing newline before
358 parsing, then here, add a newline at the end of the string
359 before sending it to ast_sendtext --DUDE */
360 res = ast_sendtext(chan, argv[2]);
361 fdprintf(agi->fd, "200 result=%d\n", res);
363 return RESULT_SUCCESS;
365 return RESULT_FAILURE;
368 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
372 return RESULT_SHOWUSAGE;
373 res = ast_recvchar(chan,atoi(argv[2]));
375 fdprintf(agi->fd, "200 result=%d (timeout)\n", res);
376 return RESULT_SUCCESS;
379 fdprintf(agi->fd, "200 result=%d\n", res);
380 return RESULT_SUCCESS;
383 fdprintf(agi->fd, "200 result=%d (hangup)\n", res);
384 return RESULT_FAILURE;
388 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
392 return RESULT_SHOWUSAGE;
393 if (!strncasecmp(argv[2],"on",2)) x = 1; else x = 0;
394 if (!strncasecmp(argv[2],"mate",4)) x = 2;
395 if (!strncasecmp(argv[2],"tdd",3)) x = 1;
396 res = ast_channel_setoption(chan,AST_OPTION_TDD,&x,sizeof(char),0);
397 fdprintf(agi->fd, "200 result=%d\n", res);
399 return RESULT_SUCCESS;
401 return RESULT_FAILURE;
404 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
408 return RESULT_SHOWUSAGE;
409 res = ast_send_image(chan, argv[2]);
410 if (!ast_check_hangup(chan))
412 fdprintf(agi->fd, "200 result=%d\n", res);
414 return RESULT_SUCCESS;
416 return RESULT_FAILURE;
419 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
422 struct ast_filestream *fs;
423 long sample_offset = 0;
427 return RESULT_SHOWUSAGE;
429 return RESULT_SHOWUSAGE;
430 if ((argc > 4) && (sscanf(argv[4], "%ld", &sample_offset) != 1))
431 return RESULT_SHOWUSAGE;
433 fs = ast_openstream(chan, argv[2], chan->language);
435 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
436 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
437 return RESULT_FAILURE;
439 ast_seekstream(fs, 0, SEEK_END);
440 max_length = ast_tellstream(fs);
441 ast_seekstream(fs, sample_offset, SEEK_SET);
442 res = ast_applystream(chan, fs);
443 res = ast_playstream(fs);
445 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
447 return RESULT_SHOWUSAGE;
449 return RESULT_FAILURE;
451 res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
452 /* this is to check for if ast_waitstream closed the stream, we probably are at
453 * the end of the stream, return that amount, else check for the amount */
454 sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
455 ast_stopstream(chan);
457 /* Stop this command, don't print a result line, as there is a new command */
458 return RESULT_SUCCESS;
460 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
462 return RESULT_SUCCESS;
464 return RESULT_FAILURE;
467 /* get option - really similar to the handle_streamfile, but with a timeout */
468 static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
471 struct ast_filestream *fs;
472 long sample_offset = 0;
475 char *edigits = NULL;
477 if ( argc < 4 || argc > 5 )
478 return RESULT_SHOWUSAGE;
484 timeout = atoi(argv[4]);
485 else if (chan->pbx->dtimeout) {
486 /* by default dtimeout is set to 5sec */
487 timeout = chan->pbx->dtimeout * 1000; //in msec
490 fs = ast_openstream(chan, argv[2], chan->language);
492 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
493 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
494 return RESULT_FAILURE;
496 if (option_verbose > 2)
497 ast_verbose(VERBOSE_PREFIX_3 "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
499 ast_seekstream(fs, 0, SEEK_END);
500 max_length = ast_tellstream(fs);
501 ast_seekstream(fs, sample_offset, SEEK_SET);
502 res = ast_applystream(chan, fs);
503 res = ast_playstream(fs);
505 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
507 return RESULT_SHOWUSAGE;
509 return RESULT_FAILURE;
511 res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
512 /* this is to check for if ast_waitstream closed the stream, we probably are at
513 * the end of the stream, return that amount, else check for the amount */
514 sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
515 ast_stopstream(chan);
517 /* Stop this command, don't print a result line, as there is a new command */
518 return RESULT_SUCCESS;
521 /* If the user didnt press a key, wait for digitTimeout*/
523 res = ast_waitfordigit_full(chan, timeout, agi->audio, agi->ctrl);
524 /* Make sure the new result is in the escape digits of the GET OPTION */
525 if ( !strchr(edigits,res) )
529 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
531 return RESULT_SUCCESS;
533 return RESULT_FAILURE;
539 /*--- handle_saynumber: Say number in various language syntaxes ---*/
540 /* Need to add option for gender here as well. Coders wanted */
541 /* While waiting, we're sending a (char *) NULL. */
542 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
547 return RESULT_SHOWUSAGE;
548 if (sscanf(argv[2], "%i", &num) != 1)
549 return RESULT_SHOWUSAGE;
550 res = ast_say_number_full(chan, num, argv[3], chan->language, (char *) NULL, agi->audio, agi->ctrl);
552 return RESULT_SUCCESS;
553 fdprintf(agi->fd, "200 result=%d\n", res);
555 return RESULT_SUCCESS;
557 return RESULT_FAILURE;
560 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
566 return RESULT_SHOWUSAGE;
567 if (sscanf(argv[2], "%i", &num) != 1)
568 return RESULT_SHOWUSAGE;
570 res = ast_say_digit_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
571 if (res == 1) /* New command */
572 return RESULT_SUCCESS;
573 fdprintf(agi->fd, "200 result=%d\n", res);
575 return RESULT_SUCCESS;
577 return RESULT_FAILURE;
580 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
585 return RESULT_SHOWUSAGE;
586 if (sscanf(argv[2], "%i", &num) != 1)
587 return RESULT_SHOWUSAGE;
588 res = ast_say_time(chan, num, argv[3], chan->language);
590 return RESULT_SUCCESS;
591 fdprintf(agi->fd, "200 result=%d\n", res);
593 return RESULT_SUCCESS;
595 return RESULT_FAILURE;
598 static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
603 return RESULT_SHOWUSAGE;
605 res = ast_say_phonetic_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
606 if (res == 1) /* New command */
607 return RESULT_SUCCESS;
608 fdprintf(agi->fd, "200 result=%d\n", res);
610 return RESULT_SUCCESS;
612 return RESULT_FAILURE;
615 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
623 return RESULT_SHOWUSAGE;
624 if (argc >= 4) timeout = atoi(argv[3]); else timeout = 0;
625 if (argc >= 5) max = atoi(argv[4]); else max = 1024;
626 res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
627 if (res == 2) /* New command */
628 return RESULT_SUCCESS;
630 fdprintf(agi->fd, "200 result=%s (timeout)\n", data);
632 fdprintf(agi->fd, "200 result=-1\n");
634 fdprintf(agi->fd, "200 result=%s\n", data);
636 return RESULT_SUCCESS;
638 return RESULT_FAILURE;
641 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
645 return RESULT_SHOWUSAGE;
646 strncpy(chan->context, argv[2], sizeof(chan->context)-1);
647 fdprintf(agi->fd, "200 result=0\n");
648 return RESULT_SUCCESS;
651 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, char **argv)
654 return RESULT_SHOWUSAGE;
655 strncpy(chan->exten, argv[2], sizeof(chan->exten)-1);
656 fdprintf(agi->fd, "200 result=0\n");
657 return RESULT_SUCCESS;
660 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char **argv)
664 return RESULT_SHOWUSAGE;
665 if (sscanf(argv[2], "%i", &pri) != 1)
666 return RESULT_SHOWUSAGE;
667 chan->priority = pri - 1;
668 fdprintf(agi->fd, "200 result=0\n");
669 return RESULT_SUCCESS;
672 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
674 struct ast_filestream *fs;
676 struct timeval tv, start;
677 long sample_offset = 0;
681 struct ast_dsp *sildet=NULL; /* silence detector dsp */
682 int totalsilence = 0;
684 int silence = 0; /* amount of silence to allow */
685 int gotsilence = 0; /* did we timeout for silence? */
686 char *silencestr=NULL;
690 /* XXX EAGI FIXME XXX */
693 return RESULT_SHOWUSAGE;
694 if (sscanf(argv[5], "%i", &ms) != 1)
695 return RESULT_SHOWUSAGE;
698 silencestr = strchr(argv[6],'s');
699 if ((argc > 7) && (!silencestr))
700 silencestr = strchr(argv[7],'s');
701 if ((argc > 8) && (!silencestr))
702 silencestr = strchr(argv[8],'s');
705 if (strlen(silencestr) > 2) {
706 if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
710 silence = atoi(silencestr);
718 rfmt = chan->readformat;
719 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
721 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
724 sildet = ast_dsp_new();
726 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
729 ast_dsp_set_threshold(sildet, 256);
732 /* backward compatibility, if no offset given, arg[6] would have been
733 * caught below and taken to be a beep, else if it is a digit then it is a
735 if ((argc >6) && (sscanf(argv[6], "%ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
736 res = ast_streamfile(chan, "beep", chan->language);
738 if ((argc > 7) && (!strchr(argv[7], '=')))
739 res = ast_streamfile(chan, "beep", chan->language);
742 res = ast_waitstream(chan, argv[4]);
744 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, 0644);
747 fdprintf(agi->fd, "200 result=%d (writefile)\n", res);
749 ast_dsp_free(sildet);
750 return RESULT_FAILURE;
754 ast_applystream(chan,fs);
755 /* really should have checks */
756 ast_seekstream(fs, sample_offset, SEEK_SET);
759 gettimeofday(&start, NULL);
760 gettimeofday(&tv, NULL);
761 while ((ms < 0) || (((tv.tv_sec - start.tv_sec) * 1000 + (tv.tv_usec - start.tv_usec)/1000) < ms)) {
762 res = ast_waitfor(chan, -1);
765 fdprintf(agi->fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
767 ast_dsp_free(sildet);
768 return RESULT_FAILURE;
772 fdprintf(agi->fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
775 ast_dsp_free(sildet);
776 return RESULT_FAILURE;
778 switch(f->frametype) {
780 if (strchr(argv[4], f->subclass)) {
781 /* This is an interrupting chracter */
782 sample_offset = ast_tellstream(fs);
783 fdprintf(agi->fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
787 ast_dsp_free(sildet);
788 return RESULT_SUCCESS;
791 case AST_FRAME_VOICE:
792 ast_writestream(fs, f);
793 /* this is a safe place to check progress since we know that fs
794 * is valid after a write, and it will then have our current
796 sample_offset = ast_tellstream(fs);
799 ast_dsp_silence(sildet, f, &dspsilence);
801 totalsilence = dspsilence;
805 if (totalsilence > silence) {
806 /* Ended happily with silence */
815 gettimeofday(&tv, NULL);
821 ast_stream_rewind(fs, silence-1000);
823 sample_offset = ast_tellstream(fs);
825 fdprintf(agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
828 fdprintf(agi->fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
831 res = ast_set_read_format(chan, rfmt);
833 ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
834 ast_dsp_free(sildet);
836 return RESULT_SUCCESS;
839 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
844 return RESULT_SHOWUSAGE;
845 if (sscanf(argv[2], "%d", &timeout) != 1)
846 return RESULT_SHOWUSAGE;
850 chan->whentohangup = time(NULL) + timeout;
852 chan->whentohangup = 0;
853 fdprintf(agi->fd, "200 result=0\n");
854 return RESULT_SUCCESS;
857 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **argv)
859 struct ast_channel *c;
861 /* no argument: hangup the current channel */
862 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
863 fdprintf(agi->fd, "200 result=1\n");
864 return RESULT_SUCCESS;
865 } else if (argc==2) {
866 /* one argument: look for info on the specified channel */
867 c = ast_channel_walk_locked(NULL);
869 if (strcasecmp(argv[1],c->name)==0) {
870 /* we have a matching channel */
871 ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
872 fdprintf(agi->fd, "200 result=1\n");
873 ast_mutex_unlock(&c->lock);
874 return RESULT_SUCCESS;
876 ast_mutex_unlock(&c->lock);
877 c = ast_channel_walk_locked(c);
879 /* if we get this far no channel name matched the argument given */
880 fdprintf(agi->fd, "200 result=-1\n");
881 return RESULT_SUCCESS;
883 return RESULT_SHOWUSAGE;
887 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, char **argv)
893 return RESULT_SHOWUSAGE;
895 if (option_verbose > 2)
896 ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
898 app = pbx_findapp(argv[1]);
901 res = pbx_exec(chan, app, argv[2], 1);
903 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
906 fdprintf(agi->fd, "200 result=%d\n", res);
911 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, char **argv)
914 char *l = NULL, *n = NULL;
916 strncpy(tmp, argv[2], sizeof(tmp) - 1);
917 ast_callerid_parse(tmp, &n, &l);
919 ast_shrink_phone_number(l);
924 ast_set_callerid(chan, l, n, NULL);
927 fdprintf(agi->fd, "200 result=1\n");
928 return RESULT_SUCCESS;
931 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, char **argv)
933 struct ast_channel *c;
935 /* no argument: supply info on the current channel */
936 fdprintf(agi->fd, "200 result=%d\n", chan->_state);
937 return RESULT_SUCCESS;
938 } else if (argc==3) {
939 /* one argument: look for info on the specified channel */
940 c = ast_channel_walk_locked(NULL);
942 if (strcasecmp(argv[2],c->name)==0) {
943 fdprintf(agi->fd, "200 result=%d\n", c->_state);
944 ast_mutex_unlock(&c->lock);
945 return RESULT_SUCCESS;
947 ast_mutex_unlock(&c->lock);
948 c = ast_channel_walk_locked(c);
950 /* if we get this far no channel name matched the argument given */
951 fdprintf(agi->fd, "200 result=-1\n");
952 return RESULT_SUCCESS;
954 return RESULT_SHOWUSAGE;
958 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
961 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
963 fdprintf(agi->fd, "200 result=1\n");
964 return RESULT_SUCCESS;
967 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
971 return RESULT_SHOWUSAGE;
972 if ((tempstr = pbx_builtin_getvar_helper(chan, argv[2])))
973 fdprintf(agi->fd, "200 result=1 (%s)\n", tempstr);
975 fdprintf(agi->fd, "200 result=0\n");
977 return RESULT_SUCCESS;
980 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, char **argv)
983 struct ast_channel *chan2=NULL;
984 if ((argc != 4) && (argc != 5))
985 return RESULT_SHOWUSAGE;
987 while((chan2 = ast_channel_walk_locked(chan2))) {
988 if (!strcmp(chan2->name, argv[4]))
990 ast_mutex_unlock(&chan2->lock);
991 chan2 = ast_channel_walk_locked(chan2);
997 pbx_substitute_variables_helper(chan2, argv[3], tmp, sizeof(tmp) - 1);
998 fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
1000 fdprintf(agi->fd, "200 result=0\n");
1002 if (chan2 && (chan2 != chan))
1003 ast_mutex_unlock(&chan2->lock);
1004 return RESULT_SUCCESS;
1007 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1013 return RESULT_SHOWUSAGE;
1016 sscanf(argv[2], "%d", &level);
1020 prefix = VERBOSE_PREFIX_4;
1023 prefix = VERBOSE_PREFIX_3;
1026 prefix = VERBOSE_PREFIX_2;
1030 prefix = VERBOSE_PREFIX_1;
1034 if (level <= option_verbose)
1035 ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
1037 fdprintf(agi->fd, "200 result=1\n");
1039 return RESULT_SUCCESS;
1042 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1047 return RESULT_SHOWUSAGE;
1048 res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
1050 fdprintf(agi->fd, "200 result=0\n");
1052 fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
1054 return RESULT_SUCCESS;
1057 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1061 return RESULT_SHOWUSAGE;
1062 res = ast_db_put(argv[2], argv[3], argv[4]);
1064 fdprintf(agi->fd, "200 result=0\n");
1066 fdprintf(agi->fd, "200 result=1\n");
1068 return RESULT_SUCCESS;
1071 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1075 return RESULT_SHOWUSAGE;
1076 res = ast_db_del(argv[2], argv[3]);
1078 fdprintf(agi->fd, "200 result=0\n");
1080 fdprintf(agi->fd, "200 result=1\n");
1082 return RESULT_SUCCESS;
1085 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1088 if ((argc < 3) || (argc > 4))
1089 return RESULT_SHOWUSAGE;
1091 res = ast_db_deltree(argv[2], argv[3]);
1093 res = ast_db_deltree(argv[2], NULL);
1096 fdprintf(agi->fd, "200 result=0\n");
1098 fdprintf(agi->fd, "200 result=1\n");
1099 return RESULT_SUCCESS;
1102 static char debug_usage[] =
1103 "Usage: agi debug\n"
1104 " Enables dumping of AGI transactions for debugging purposes\n";
1106 static char no_debug_usage[] =
1107 "Usage: agi no debug\n"
1108 " Disables dumping of AGI transactions for debugging purposes\n";
1110 static int agi_do_debug(int fd, int argc, char *argv[])
1113 return RESULT_SHOWUSAGE;
1115 ast_cli(fd, "AGI Debugging Enabled\n");
1116 return RESULT_SUCCESS;
1119 static int agi_no_debug(int fd, int argc, char *argv[])
1122 return RESULT_SHOWUSAGE;
1124 ast_cli(fd, "AGI Debugging Disabled\n");
1125 return RESULT_SUCCESS;
1128 static struct ast_cli_entry cli_debug =
1129 { { "agi", "debug", NULL }, agi_do_debug, "Enable AGI debugging", debug_usage };
1131 static struct ast_cli_entry cli_no_debug =
1132 { { "agi", "no", "debug", NULL }, agi_no_debug, "Disable AGI debugging", no_debug_usage };
1134 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
1136 fdprintf(agi->fd, "200 result=0\n");
1137 return RESULT_SUCCESS;
1140 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
1142 if (!strncasecmp(argv[2],"on",2)) {
1144 ast_moh_start(chan, argv[3]);
1146 ast_moh_start(chan, NULL);
1148 if (!strncasecmp(argv[2],"off",3)) {
1151 fdprintf(agi->fd, "200 result=0\n");
1152 return RESULT_SUCCESS;
1155 static char usage_setmusic[] =
1156 " Usage: SET MUSIC ON <on|off> <class>\n"
1157 " Enables/Disables the music on hold generator. If <class> is\n"
1158 " not specified then the default music on hold class will be used.\n"
1159 " Always returns 0\n";
1161 static char usage_dbput[] =
1162 " Usage: DATABASE PUT <family> <key> <value>\n"
1163 " Adds or updates an entry in the Asterisk database for a\n"
1164 " given family, key, and value.\n"
1165 " Returns 1 if succesful, 0 otherwise\n";
1167 static char usage_dbget[] =
1168 " Usage: DATABASE GET <family> <key>\n"
1169 " Retrieves an entry in the Asterisk database for a\n"
1170 " given family and key.\n"
1171 " Returns 0 if <key> is not set. Returns 1 if <key>\n"
1172 " is set and returns the variable in parenthesis\n"
1173 " example return code: 200 result=1 (testvariable)\n";
1175 static char usage_dbdel[] =
1176 " Usage: DATABASE DEL <family> <key>\n"
1177 " Deletes an entry in the Asterisk database for a\n"
1178 " given family and key.\n"
1179 " Returns 1 if succesful, 0 otherwise\n";
1181 static char usage_dbdeltree[] =
1182 " Usage: DATABASE DELTREE <family> [keytree]\n"
1183 " Deletes a family or specific keytree withing a family\n"
1184 " in the Asterisk database.\n"
1185 " Returns 1 if succesful, 0 otherwise\n";
1187 static char usage_verbose[] =
1188 " Usage: VERBOSE <message> <level>\n"
1189 " Sends <message> to the console via verbose message system.\n"
1190 " <level> is the the verbose level (1-4)\n"
1191 " Always returns 1\n";
1193 static char usage_getvariable[] =
1194 " Usage: GET VARIABLE <variablename>\n"
1195 " Returns 0 if <variablename> is not set. Returns 1 if <variablename>\n"
1196 " is set and returns the variable in parenthesis\n"
1197 " example return code: 200 result=1 (testvariable)\n";
1199 static char usage_getvariablefull[] =
1200 " Usage: GET FULL VARIABLE <variablename> [<channel name>]\n"
1201 " Returns 0 if <variablename> is not set or channel does not exist. Returns 1\n"
1202 "if <variablename> is set and returns the variable in parenthesis. Understands\n"
1203 "complex variable names and builtin variables, unlike GET VARIABLE.\n"
1204 " example return code: 200 result=1 (testvariable)\n";
1206 static char usage_setvariable[] =
1207 " Usage: SET VARIABLE <variablename> <value>\n";
1209 static char usage_channelstatus[] =
1210 " Usage: CHANNEL STATUS [<channelname>]\n"
1211 " Returns the status of the specified channel.\n"
1212 " If no channel name is given the returns the status of the\n"
1213 " current channel.\n"
1215 " 0 Channel is down and available\n"
1216 " 1 Channel is down, but reserved\n"
1217 " 2 Channel is off hook\n"
1218 " 3 Digits (or equivalent) have been dialed\n"
1219 " 4 Line is ringing\n"
1220 " 5 Remote end is ringing\n"
1222 " 7 Line is busy\n";
1224 static char usage_setcallerid[] =
1225 " Usage: SET CALLERID <number>\n"
1226 " Changes the callerid of the current channel.\n";
1228 static char usage_exec[] =
1229 " Usage: EXEC <application> <options>\n"
1230 " Executes <application> with given <options>.\n"
1231 " Returns whatever the application returns, or -2 on failure to find application\n";
1233 static char usage_hangup[] =
1234 " Usage: HANGUP [<channelname>]\n"
1235 " Hangs up the specified channel.\n"
1236 " If no channel name is given, hangs up the current channel\n";
1238 static char usage_answer[] =
1240 " Answers channel if not already in answer state. Returns -1 on\n"
1241 " channel failure, or 0 if successful.\n";
1243 static char usage_waitfordigit[] =
1244 " Usage: WAIT FOR DIGIT <timeout>\n"
1245 " Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
1246 " Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
1247 " the numerical value of the ascii of the digit if one is received. Use -1\n"
1248 " for the timeout value if you desire the call to block indefinitely.\n";
1250 static char usage_sendtext[] =
1251 " Usage: SEND TEXT \"<text to send>\"\n"
1252 " Sends the given text on a channel. Most channels do not support the\n"
1253 " transmission of text. Returns 0 if text is sent, or if the channel does not\n"
1254 " support text transmission. Returns -1 only on error/hangup. Text\n"
1255 " consisting of greater than one word should be placed in quotes since the\n"
1256 " command only accepts a single argument.\n";
1258 static char usage_recvchar[] =
1259 " Usage: RECEIVE CHAR <timeout>\n"
1260 " Receives a character of text on a channel. Specify timeout to be the\n"
1261 " maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
1262 " do not support the reception of text. Returns the decimal value of the character\n"
1263 " if one is received, or 0 if the channel does not support text reception. Returns\n"
1264 " -1 only on error/hangup.\n";
1266 static char usage_tddmode[] =
1267 " Usage: TDD MODE <on|off>\n"
1268 " Enable/Disable TDD transmission/reception on a channel. Returns 1 if\n"
1269 " successful, or 0 if channel is not TDD-capable.\n";
1271 static char usage_sendimage[] =
1272 " Usage: SEND IMAGE <image>\n"
1273 " Sends the given image on a channel. Most channels do not support the\n"
1274 " transmission of images. Returns 0 if image is sent, or if the channel does not\n"
1275 " support image transmission. Returns -1 only on error/hangup. Image names\n"
1276 " should not include extensions.\n";
1278 static char usage_streamfile[] =
1279 " Usage: STREAM FILE <filename> <escape digits> [sample offset]\n"
1280 " Send the given file, allowing playback to be interrupted by the given\n"
1281 " digits, if any. Use double quotes for the digits if you wish none to be\n"
1282 " permitted. If sample offset is provided then the audio will seek to sample\n"
1283 " offset before play starts. Returns 0 if playback completes without a digit\n"
1284 " being pressed, or the ASCII numerical value of the digit if one was pressed,\n"
1285 " or -1 on error or if the channel was disconnected. Remember, the file\n"
1286 " extension must not be included in the filename.\n";
1288 static char usage_getoption[] =
1289 " Usage: GET OPTION <filename> <escape_digits> [timeout]\n"
1290 " Exactly like the STREAM FILE but used with a timeout option\n";
1292 static char usage_saynumber[] =
1293 " Usage: SAY NUMBER <number> <escape digits>\n"
1294 " Say a given number, returning early if any of the given DTMF digits\n"
1295 " are received on the channel. Returns 0 if playback completes without a digit\n"
1296 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
1297 " -1 on error/hangup.\n";
1299 static char usage_saydigits[] =
1300 " Usage: SAY DIGITS <number> <escape digits>\n"
1301 " Say a given digit string, returning early if any of the given DTMF digits\n"
1302 " are received on the channel. Returns 0 if playback completes without a digit\n"
1303 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
1304 " -1 on error/hangup.\n";
1306 static char usage_saytime[] =
1307 " Usage: SAY TIME <time> <escape digits>\n"
1308 " Say a given time, returning early if any of the given DTMF digits are\n"
1309 " received on the channel. <time> is number of seconds elapsed since 00:00:00\n"
1310 " on January 1, 1970, Coordinated Universal Time (UTC). Returns 0 if playback\n"
1311 " completes without a digit being pressed, or the ASCII numerical value of the\n"
1312 " digit if one was pressed or -1 on error/hangup.\n";
1314 static char usage_sayphonetic[] =
1315 " Usage: SAY PHONETIC <string> <escape digits>\n"
1316 " Say a given character string with phonetics, returning early if any of the given DTMF digits\n"
1317 " are received on the channel. Returns 0 if playback completes without a digit\n"
1318 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
1319 " -1 on error/hangup.\n";
1321 static char usage_getdata[] =
1322 " Usage: GET DATA <file to be streamed> [timeout] [max digits]\n"
1323 " Stream the given file, and recieve DTMF data. Returns the digits recieved\n"
1324 "from the channel at the other end.\n";
1326 static char usage_setcontext[] =
1327 " Usage: SET CONTEXT <desired context>\n"
1328 " Sets the context for continuation upon exiting the application.\n";
1330 static char usage_setextension[] =
1331 " Usage: SET EXTENSION <new extension>\n"
1332 " Changes the extension for continuation upon exiting the application.\n";
1334 static char usage_setpriority[] =
1335 " Usage: SET PRIORITY <num>\n"
1336 " Changes the priority for continuation upon exiting the application.\n";
1338 static char usage_recordfile[] =
1339 " Usage: RECORD FILE <filename> <format> <escape digits> <timeout> [offset samples] [BEEP] [s=silence]\n"
1340 " Record to a file until a given dtmf digit in the sequence is received\n"
1341 " Returns -1 on hangup or error. The format will specify what kind of file\n"
1342 " will be recorded. The timeout is the maximum record time in milliseconds, or\n"
1343 " -1 for no timeout. Offset samples is optional, and if provided will seek to\n"
1344 " the offset without exceeding the end of the file. \"silence\" is the number\n"
1345 " of seconds of silence allowed before the function returns despite the\n"
1346 " lack of dtmf digits or reaching timeout. Silence value must be\n"
1347 " preceeded by \"s=\" and is optional.\n";
1350 static char usage_autohangup[] =
1351 " Usage: SET AUTOHANGUP <time>\n"
1352 " Cause the channel to automatically hangup at <time> seconds in the\n"
1353 "future. Of course it can be hungup before then as well. Setting to\n"
1354 "0 will cause the autohangup feature to be disabled on this channel.\n";
1356 static char usage_noop[] =
1360 static agi_command commands[MAX_COMMANDS] = {
1361 { { "answer", NULL }, handle_answer, "Asserts answer", usage_answer },
1362 { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
1363 { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
1364 { { "receive", "char", NULL }, handle_recvchar, "Receives text from channels supporting it", usage_recvchar },
1365 { { "tdd", "mode", NULL }, handle_tddmode, "Sends text to channels supporting it", usage_tddmode },
1366 { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
1367 { { "get", "option", NULL }, handle_getoption, "Stream File", usage_getoption },
1368 { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
1369 { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
1370 { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
1371 { { "say", "phonetic", NULL }, handle_sayphonetic, "Says a given character string with phonetics", usage_sayphonetic },
1372 { { "say", "time", NULL }, handle_saytime, "Says a given time", usage_saytime },
1373 { { "get", "data", NULL }, handle_getdata, "Gets data on a channel", usage_getdata },
1374 { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
1375 { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
1376 { { "set", "priority", NULL }, handle_setpriority, "Prioritizes the channel", usage_setpriority },
1377 { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
1378 { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
1379 { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
1380 { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
1381 { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
1382 { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus },
1383 { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable },
1384 { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable },
1385 { { "get", "full", "variable", NULL }, handle_getvariablefull, "Evaluates a channel expression", usage_getvariablefull },
1386 { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose },
1387 { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget },
1388 { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput },
1389 { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel },
1390 { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree },
1391 { { "noop", NULL }, handle_noop, "Does nothing", usage_noop },
1392 { { "set", "music", NULL }, handle_setmusic, "Enable/Disable Music on hold generator", usage_setmusic }
1395 static void join(char *s, size_t len, char *w[])
1398 /* Join words into a string */
1403 for (x=0;w[x];x++) {
1405 strncat(s, " ", len - strlen(s) - 1);
1406 strncat(s, w[x], len - strlen(s) - 1);
1410 static int help_workhorse(int fd, char *match[])
1415 struct agi_command *e;
1417 join(matchstr, sizeof(matchstr), match);
1418 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1419 if (!commands[x].cmda[0]) break;
1422 join(fullcmd, sizeof(fullcmd), e->cmda);
1423 /* Hide commands that start with '_' */
1424 if (fullcmd[0] == '_')
1427 if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1431 ast_cli(fd, "%20.20s %s\n", fullcmd, e->summary);
1436 int agi_register(agi_command *agi)
1439 for (x=0;x<MAX_COMMANDS - 1;x++) {
1440 if (commands[x].cmda[0] == agi->cmda[0]) {
1441 ast_log(LOG_WARNING, "Command already registered!\n");
1445 for (x=0;x<MAX_COMMANDS - 1;x++) {
1446 if (!commands[x].cmda[0]) {
1451 ast_log(LOG_WARNING, "No more room for new commands!\n");
1455 void agi_unregister(agi_command *agi)
1458 for (x=0;x<MAX_COMMANDS - 1;x++) {
1459 if (commands[x].cmda[0] == agi->cmda[0]) {
1460 memset(&commands[x], 0, sizeof(agi_command));
1465 static agi_command *find_command(char *cmds[], int exact)
1470 for (x=0;x < sizeof(commands) / sizeof(commands[0]);x++) {
1471 if (!commands[x].cmda[0]) break;
1472 /* start optimistic */
1474 for (y=0;match && cmds[y]; y++) {
1475 /* If there are no more words in the command (and we're looking for
1476 an exact match) or there is a difference between the two words,
1477 then this is not a match */
1478 if (!commands[x].cmda[y] && !exact)
1480 /* don't segfault if the next part of a command doesn't exist */
1481 if (!commands[x].cmda[y]) return NULL;
1482 if (strcasecmp(commands[x].cmda[y], cmds[y]))
1485 /* If more words are needed to complete the command then this is not
1486 a candidate (unless we're looking for a really inexact answer */
1487 if ((exact > -1) && commands[x].cmda[y])
1490 return &commands[x];
1496 static int parse_args(char *s, int *max, char *argv[])
1508 /* If it's escaped, put a literal quote */
1513 if (quoted && whitespace) {
1514 /* If we're starting a quote, coming off white space start a new word, too */
1522 if (!quoted && !escaped) {
1523 /* If we're not quoted, mark this as whitespace, and
1524 end the previous argument */
1528 /* Otherwise, just treat it as anything else */
1532 /* If we're escaped, print a literal, otherwise enable escaping */
1542 if (x >= MAX_ARGS -1) {
1543 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1546 /* Coming off of whitespace, start the next argument */
1555 /* Null terminate */
1562 static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf)
1564 char *argv[MAX_ARGS];
1569 parse_args(buf, &argc, argv);
1572 for (x=0;x<argc;x++)
1573 fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
1575 c = find_command(argv, 0);
1577 res = c->handler(chan, agi, argc, argv);
1579 case RESULT_SHOWUSAGE:
1580 fdprintf(agi->fd, "520-Invalid command syntax. Proper usage follows:\n");
1581 fdprintf(agi->fd, c->usage);
1582 fdprintf(agi->fd, "520 End of proper usage.\n");
1584 case AST_PBX_KEEPALIVE:
1585 /* We've been asked to keep alive, so do so */
1586 return AST_PBX_KEEPALIVE;
1588 case RESULT_FAILURE:
1589 /* They've already given the failure. We've been hung up on so handle this
1594 fdprintf(agi->fd, "510 Invalid or unknown command\n");
1599 static int run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid, int dead)
1601 struct ast_channel *c;
1604 int returnstatus = 0;
1605 struct ast_frame *f;
1608 /* how many times we'll retry if ast_waitfor_nandfs will return without either
1609 channel or file descriptor in case select is interrupted by a system call (EINTR) */
1612 if (!(readf = fdopen(agi->ctrl, "r"))) {
1613 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
1620 setup_env(chan, request, agi->fd, (agi->audio > -1));
1623 c = ast_waitfor_nandfds(&chan, dead ? 0 : 1, &agi->ctrl, 1, NULL, &outfd, &ms);
1626 /* Idle the channel until we get a command */
1629 ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
1633 /* If it's voice, write it to the audio pipe */
1634 if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
1635 /* Write, ignoring errors */
1636 write(agi->audio, f->data, f->datalen);
1640 } else if (outfd > -1) {
1642 if (!fgets(buf, sizeof(buf), readf)) {
1643 /* Program terminated */
1646 if (option_verbose > 2)
1647 ast_verbose(VERBOSE_PREFIX_3 "AGI Script %s completed, returning %d\n", request, returnstatus);
1648 /* No need to kill the pid anymore, since they closed us */
1652 /* get rid of trailing newline, if any */
1653 if (*buf && buf[strlen(buf) - 1] == '\n')
1654 buf[strlen(buf) - 1] = 0;
1656 ast_verbose("AGI Rx << %s\n", buf);
1657 returnstatus |= agi_handle_command(chan, agi, buf);
1658 /* If the handle_command returns -1, we need to stop */
1659 if ((returnstatus < 0) || (returnstatus == AST_PBX_KEEPALIVE)) {
1664 ast_log(LOG_WARNING, "No channel, no fd?\n");
1670 /* Notify process */
1674 return returnstatus;
1677 static int handle_showagi(int fd, int argc, char *argv[]) {
1678 struct agi_command *e;
1681 return RESULT_SHOWUSAGE;
1683 e = find_command(argv + 2, 1);
1685 ast_cli(fd, e->usage);
1687 if (find_command(argv + 2, -1)) {
1688 return help_workhorse(fd, argv + 1);
1690 join(fullcmd, sizeof(fullcmd), argv+1);
1691 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1695 return help_workhorse(fd, NULL);
1697 return RESULT_SUCCESS;
1700 static int handle_dumpagihtml(int fd, int argc, char *argv[]) {
1701 struct agi_command *e;
1708 return RESULT_SHOWUSAGE;
1710 if (!(htmlfile = fopen(argv[2], "wt"))) {
1711 ast_cli(fd, "Could not create file '%s'\n", argv[2]);
1712 return RESULT_SHOWUSAGE;
1715 fprintf(htmlfile, "<HTML>\n<HEAD>\n<TITLE>AGI Commands</TITLE>\n</HEAD>\n");
1716 fprintf(htmlfile, "<BODY>\n<CENTER><B><H1>AGI Commands</H1></B></CENTER>\n\n");
1719 fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
1721 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1723 if (!commands[x].cmda[0]) break;
1726 join(fullcmd, sizeof(fullcmd), e->cmda);
1727 /* Hide commands that start with '_' */
1728 if (fullcmd[0] == '_')
1731 fprintf(htmlfile, "<TR><TD><TABLE BORDER=\"1\" CELLPADDING=\"5\" WIDTH=\"100%%\">\n");
1732 fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TD></TR>\n", fullcmd,e->summary);
1736 tempstr = strsep(&stringp, "\n");
1738 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">%s</TD></TR>\n", tempstr);
1740 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
1741 while ((tempstr = strsep(&stringp, "\n")) != NULL) {
1742 fprintf(htmlfile, "%s<BR>\n",tempstr);
1745 fprintf(htmlfile, "</TD></TR>\n");
1746 fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
1750 fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
1752 ast_cli(fd, "AGI HTML Commands Dumped to: %s\n", argv[2]);
1753 return RESULT_SUCCESS;
1756 static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced, int dead)
1759 struct localuser *u;
1760 char *argv[MAX_ARGS];
1762 char *tmp = (char *)buf;
1769 if (!data || ast_strlen_zero(data)) {
1770 ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
1773 strncpy(buf, data, sizeof(buf) - 1);
1775 memset(&agi, 0, sizeof(agi));
1776 while ((stringp = strsep(&tmp, "|"))) {
1777 argv[argc++] = stringp;
1783 /* Answer if need be */
1784 if (chan->_state != AST_STATE_UP) {
1785 if (ast_answer(chan)) {
1786 LOCAL_USER_REMOVE(u);
1791 res = launch_script(argv[0], argv, fds, enhanced ? &efd : NULL, &pid);
1796 res = run_agi(chan, argv[0], &agi, pid, dead);
1801 LOCAL_USER_REMOVE(u);
1805 static int agi_exec(struct ast_channel *chan, void *data)
1807 if (chan->_softhangup)
1808 ast_log(LOG_WARNING, "If you want to run AGI on hungup channels you should use DeadAGI!\n");
1809 return agi_exec_full(chan, data, 0, 0);
1812 static int eagi_exec(struct ast_channel *chan, void *data)
1816 if (chan->_softhangup)
1817 ast_log(LOG_WARNING, "If you want to run AGI on hungup channels you should use DeadAGI!\n");
1818 readformat = chan->readformat;
1819 if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
1820 ast_log(LOG_WARNING, "Unable to set channel '%s' to linear mode\n", chan->name);
1823 res = agi_exec_full(chan, data, 1, 0);
1825 if (ast_set_read_format(chan, readformat)) {
1826 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %s\n", chan->name, ast_getformatname(readformat));
1832 static int deadagi_exec(struct ast_channel *chan, void *data)
1834 return agi_exec_full(chan, data, 0, 1);
1837 static char showagi_help[] =
1838 "Usage: show agi [topic]\n"
1839 " When called with a topic as an argument, displays usage\n"
1840 " information on the given command. If called without a\n"
1841 " topic, it provides a list of AGI commands.\n";
1844 static char dumpagihtml_help[] =
1845 "Usage: dump agihtml <filename>\n"
1846 " Dumps the agi command list in html format to given filename\n";
1848 static struct ast_cli_entry showagi =
1849 { { "show", "agi", NULL }, handle_showagi, "Show AGI commands or specific help", showagi_help };
1851 static struct ast_cli_entry dumpagihtml =
1852 { { "dump", "agihtml", NULL }, handle_dumpagihtml, "Dumps a list of agi command in html format", dumpagihtml_help };
1854 int unload_module(void)
1856 STANDARD_HANGUP_LOCALUSERS;
1857 ast_cli_unregister(&showagi);
1858 ast_cli_unregister(&dumpagihtml);
1859 ast_cli_unregister(&cli_debug);
1860 ast_cli_unregister(&cli_no_debug);
1861 ast_unregister_application(eapp);
1862 ast_unregister_application(deadapp);
1863 return ast_unregister_application(app);
1866 int load_module(void)
1868 ast_cli_register(&showagi);
1869 ast_cli_register(&dumpagihtml);
1870 ast_cli_register(&cli_debug);
1871 ast_cli_register(&cli_no_debug);
1872 ast_register_application(deadapp, deadagi_exec, deadsynopsis, descrip);
1873 ast_register_application(eapp, eagi_exec, esynopsis, descrip);
1874 return ast_register_application(app, agi_exec, synopsis, descrip);
1877 char *description(void)
1885 STANDARD_USECOUNT(res);
1891 return ASTERISK_GPL_KEY;