2 * Asterisk -- A telephony toolkit for Linux.
4 * Asterisk Gateway Interface
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
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>
26 #include <sys/signal.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"
46 /* Recycle some stuff from the CLI interface */
47 #define fdprintf ast_cli
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 */
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) */
63 /* Detailed usage information */
67 static char *tdesc = "Asterisk Gateway Interface (AGI)";
69 static char *app = "AGI";
71 static char *eapp = "EAGI";
73 static char *synopsis = "Executes an AGI compliant application";
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";
89 #define TONE_BLOCK_SIZE 200
91 static int launch_script(char *script, char *args, int *fds, int *efd, int *opid)
100 if (script[0] != '/') {
101 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_AGI_DIR, script);
105 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
109 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
116 ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
123 res = fcntl(audio[1], F_GETFL);
125 res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
127 ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
139 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
143 /* Redirect stdin and out, provide enhanced audio channel if desired */
144 dup2(fromast[0], STDIN_FILENO);
145 dup2(toast[1], STDOUT_FILENO);
147 dup2(audio[0], STDERR_FILENO + 1);
149 close(STDERR_FILENO + 1);
151 /* Close everything but stdin/out/error */
152 for (x=STDERR_FILENO + 2;x<1024;x++)
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));
160 if (option_verbose > 2)
161 ast_verbose(VERBOSE_PREFIX_3 "Launched AGI Script %s\n", script);
167 /* close what we're not using in the parent */
175 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced)
177 /* Print initial environment, with agi_request always being the first
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);
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 : "");
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");
196 /* User information */
197 fdprintf(fd, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
199 /* End with empty return */
203 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
207 if (chan->_state != AST_STATE_UP) {
208 /* Answer the chan */
209 res = ast_answer(chan);
211 fdprintf(agi->fd, "200 result=%d\n", res);
213 return RESULT_SUCCESS;
215 return RESULT_FAILURE;
218 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
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);
229 return RESULT_SUCCESS;
231 return RESULT_FAILURE;
234 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
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);
249 return RESULT_SUCCESS;
251 return RESULT_FAILURE;
254 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
258 return RESULT_SHOWUSAGE;
259 res = ast_recvchar(chan,atoi(argv[2]));
261 fdprintf(agi->fd, "200 result=%d (timeout)\n", res);
262 return RESULT_SUCCESS;
265 fdprintf(agi->fd, "200 result=%d\n", res);
266 return RESULT_SUCCESS;
269 fdprintf(agi->fd, "200 result=%d (hangup)\n", res);
270 return RESULT_FAILURE;
274 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
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);
285 return RESULT_SUCCESS;
287 return RESULT_FAILURE;
290 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
294 return RESULT_SHOWUSAGE;
295 res = ast_send_image(chan, argv[2]);
296 if (!ast_check_hangup(chan))
298 fdprintf(agi->fd, "200 result=%d\n", res);
300 return RESULT_SUCCESS;
302 return RESULT_FAILURE;
305 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
308 struct ast_filestream *fs;
309 long sample_offset = 0;
313 return RESULT_SHOWUSAGE;
315 return RESULT_SHOWUSAGE;
316 if ((argc > 4) && (sscanf(argv[4], "%ld", &sample_offset) != 1))
317 return RESULT_SHOWUSAGE;
319 fs = ast_openstream(chan, argv[2], chan->language);
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;
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);
331 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
333 return RESULT_SHOWUSAGE;
335 return RESULT_FAILURE;
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);
343 /* Stop this command, don't print a result line, as there is a new command */
344 return RESULT_SUCCESS;
346 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
348 return RESULT_SUCCESS;
350 return RESULT_FAILURE;
353 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
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);
363 return RESULT_SUCCESS;
364 fdprintf(agi->fd, "200 result=%d\n", res);
366 return RESULT_SUCCESS;
368 return RESULT_FAILURE;
371 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
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);
384 return RESULT_SUCCESS;
386 return RESULT_FAILURE;
389 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
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;
404 fdprintf(agi->fd, "200 result=%s (timeout)\n", data);
406 fdprintf(agi->fd, "200 result=%s\n", data);
408 return RESULT_SUCCESS;
410 return RESULT_FAILURE;
413 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
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;
423 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, char **argv)
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;
432 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char **argv)
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;
444 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
446 struct ast_filestream *fs;
448 struct timeval tv, start;
449 long sample_offset = 0;
453 struct ast_dsp *sildet; /* silence detector dsp */
454 int totalsilence = 0;
456 int silence = 0; /* amount of silence to allow */
457 int gotsilence = 0; /* did we timeout for silence? */
462 /* XXX EAGI FIXME XXX */
465 return RESULT_SHOWUSAGE;
466 if (sscanf(argv[5], "%i", &ms) != 1)
467 return RESULT_SHOWUSAGE;
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');
477 if (strlen(silencestr) > 2) {
478 if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
482 silence = atoi(silencestr);
490 rfmt = chan->readformat;
491 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
493 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
496 sildet = ast_dsp_new();
498 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
501 ast_dsp_set_threshold(sildet, 256);
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
507 if ((argc >6) && (sscanf(argv[6], "%ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
508 res = ast_streamfile(chan, "beep", chan->language);
510 if ((argc > 7) && (!strchr(argv[7], '=')))
511 res = ast_streamfile(chan, "beep", chan->language);
514 res = ast_waitstream(chan, argv[4]);
516 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY, 0, 0644);
519 fdprintf(agi->fd, "200 result=%d (writefile)\n", res);
520 return RESULT_FAILURE;
524 ast_applystream(chan,fs);
525 /* really should have checks */
526 ast_seekstream(fs, sample_offset, SEEK_SET);
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);
535 fdprintf(agi->fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
536 return RESULT_FAILURE;
540 fdprintf(agi->fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
542 return RESULT_FAILURE;
544 switch(f->frametype) {
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);
552 return RESULT_SUCCESS;
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
560 sample_offset = ast_tellstream(fs);
563 ast_dsp_silence(sildet, f, &dspsilence);
565 totalsilence = dspsilence;
569 if (totalsilence > silence) {
570 /* Ended happily with silence */
579 gettimeofday(&tv, NULL);
585 ast_stream_rewind(fs, silence-1000);
588 fdprintf(agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
591 fdprintf(agi->fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
594 res = ast_set_read_format(chan, rfmt);
596 ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
597 ast_dsp_free(sildet);
599 return RESULT_SUCCESS;
602 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
607 return RESULT_SHOWUSAGE;
608 if (sscanf(argv[2], "%d", &timeout) != 1)
609 return RESULT_SHOWUSAGE;
613 chan->whentohangup = time(NULL) + timeout;
615 chan->whentohangup = 0;
616 fdprintf(agi->fd, "200 result=0\n");
617 return RESULT_SUCCESS;
620 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **argv)
622 struct ast_channel *c;
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);
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;
638 c = ast_channel_walk(c);
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;
644 return RESULT_SHOWUSAGE;
648 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, char **argv)
654 return RESULT_SHOWUSAGE;
656 if (option_verbose > 2)
657 ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
659 app = pbx_findapp(argv[1]);
662 res = pbx_exec(chan, app, argv[2], 1);
664 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
667 fdprintf(agi->fd, "200 result=%d\n", res);
672 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, char **argv)
675 ast_set_callerid(chan, argv[2], 0);
677 /* strncpy(chan->callerid, argv[2], sizeof(chan->callerid)-1);
678 */ fdprintf(agi->fd, "200 result=1\n");
679 return RESULT_SUCCESS;
682 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, char **argv)
684 struct ast_channel *c;
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);
693 if (strcasecmp(argv[2],c->name)==0) {
694 fdprintf(agi->fd, "200 result=%d\n", c->_state);
695 return RESULT_SUCCESS;
697 c = ast_channel_walk(c);
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;
703 return RESULT_SHOWUSAGE;
707 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
710 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
712 fdprintf(agi->fd, "200 result=1\n");
713 return RESULT_SUCCESS;
716 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
720 if ((tempstr = pbx_builtin_getvar_helper(chan, argv[2])) )
721 fdprintf(agi->fd, "200 result=1 (%s)\n", tempstr);
723 fdprintf(agi->fd, "200 result=0\n");
725 return RESULT_SUCCESS;
728 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **argv)
734 return RESULT_SHOWUSAGE;
737 sscanf(argv[2], "%d", &level);
741 prefix = VERBOSE_PREFIX_4;
744 prefix = VERBOSE_PREFIX_3;
747 prefix = VERBOSE_PREFIX_2;
751 prefix = VERBOSE_PREFIX_1;
755 if (level <= option_verbose)
756 ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
758 fdprintf(agi->fd, "200 result=1\n");
760 return RESULT_SUCCESS;
763 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, char **argv)
768 return RESULT_SHOWUSAGE;
769 res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
771 fdprintf(agi->fd, "200 result=0\n");
773 fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
775 return RESULT_SUCCESS;
778 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, char **argv)
782 return RESULT_SHOWUSAGE;
783 res = ast_db_put(argv[2], argv[3], argv[4]);
785 fdprintf(agi->fd, "200 result=0\n");
787 fdprintf(agi->fd, "200 result=1\n");
789 return RESULT_SUCCESS;
792 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, char **argv)
796 return RESULT_SHOWUSAGE;
797 res = ast_db_del(argv[2], argv[3]);
799 fdprintf(agi->fd, "200 result=0\n");
801 fdprintf(agi->fd, "200 result=1\n");
803 return RESULT_SUCCESS;
806 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char **argv)
809 if ((argc < 3) || (argc > 4))
810 return RESULT_SHOWUSAGE;
812 res = ast_db_deltree(argv[2], argv[3]);
814 res = ast_db_deltree(argv[2], NULL);
817 fdprintf(agi->fd, "200 result=0\n");
819 fdprintf(agi->fd, "200 result=1\n");
820 return RESULT_SUCCESS;
823 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
825 fdprintf(agi->fd, "200 result=0\n");
826 return RESULT_SUCCESS;
829 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
831 if (!strncasecmp(argv[2],"on",2)) {
833 ast_moh_start(chan, argv[3]);
835 ast_moh_start(chan, NULL);
837 if (!strncasecmp(argv[2],"off",3)) {
840 fdprintf(agi->fd, "200 result=0\n");
841 return RESULT_SUCCESS;
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";
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";
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";
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";
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";
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";
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";
888 static char usage_setvariable[] =
889 " Usage: SET VARIABLE <variablename> <value>\n";
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"
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"
906 static char usage_setcallerid[] =
907 " Usage: SET CALLERID <number>\n"
908 " Changes the callerid of the current channel.\n";
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";
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";
920 static char usage_answer[] =
922 " Answers channel if not already in answer state. Returns -1 on\n"
923 " channel failure, or 0 if successful.\n";
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";
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";
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";
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";
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";
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";
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";
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";
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";
989 static char usage_setcontext[] =
990 " Usage: SET CONTEXT <desired context>\n"
991 " Sets the context for continuation upon exiting the application.\n";
993 static char usage_setextension[] =
994 " Usage: SET EXTENSION <new extension>\n"
995 " Changes the extension for continuation upon exiting the application.\n";
997 static char usage_setpriority[] =
998 " Usage: SET PRIORITY <num>\n"
999 " Changes the priority for continuation upon exiting the application.\n";
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";
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";
1019 static char usage_noop[] =
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 }
1054 static void join(char *s, int len, char *w[])
1057 /* Join words into a string */
1059 for (x=0;w[x];x++) {
1061 strncat(s, " ", len - strlen(s));
1062 strncat(s, w[x], len - strlen(s));
1066 static int help_workhorse(int fd, char *match[])
1071 struct agi_command *e;
1073 join(matchstr, sizeof(matchstr), match);
1074 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1077 join(fullcmd, sizeof(fullcmd), e->cmda);
1078 /* Hide commands that start with '_' */
1079 if (fullcmd[0] == '_')
1082 if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1086 ast_cli(fd, "%20.20s %s\n", fullcmd, e->summary);
1091 static agi_command *find_command(char *cmds[], int exact)
1096 for (x=0;x < sizeof(commands) / sizeof(commands[0]);x++) {
1097 /* start optimistic */
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)
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]))
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])
1115 return &commands[x];
1121 static int parse_args(char *s, int *max, char *argv[])
1133 /* If it's escaped, put a literal quote */
1138 if (quoted && whitespace) {
1139 /* If we're starting a quote, coming off white space start a new word, too */
1147 if (!quoted && !escaped) {
1148 /* If we're not quoted, mark this as whitespace, and
1149 end the previous argument */
1153 /* Otherwise, just treat it as anything else */
1157 /* If we're escaped, print a literal, otherwise enable escaping */
1167 if (x >= MAX_ARGS -1) {
1168 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1171 /* Coming off of whitespace, start the next argument */
1180 /* Null terminate */
1187 static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf)
1189 char *argv[MAX_ARGS];
1194 parse_args(buf, &argc, argv);
1197 for (x=0;x<argc;x++)
1198 fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
1200 c = find_command(argv, 0);
1202 res = c->handler(chan, agi, argc, argv);
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");
1209 case RESULT_FAILURE:
1210 /* They've already given the failure. We've been hung up on so handle this
1215 fdprintf(agi->fd, "510 Invalid or unknown command\n");
1220 static int run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid)
1222 struct ast_channel *c;
1225 int returnstatus = 0;
1226 struct ast_frame *f;
1229 if (!(readf = fdopen(agi->ctrl, "r"))) {
1230 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
1235 setup_env(chan, request, agi->fd, (agi->audio > -1));
1238 c = ast_waitfor_nandfds(&chan, 1, &agi->ctrl, 1, NULL, &outfd, &ms);
1240 /* Idle the channel until we get a command */
1243 ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
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);
1254 } else if (outfd > -1) {
1255 if (!fgets(buf, sizeof(buf), readf)) {
1256 /* Program terminated */
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 */
1265 /* get rid of trailing newline, if any */
1266 if (*buf && buf[strlen(buf) - 1] == '\n')
1267 buf[strlen(buf) - 1] = 0;
1269 returnstatus |= agi_handle_command(chan, agi, buf);
1270 /* If the handle_command returns -1, we need to stop */
1271 if (returnstatus < 0) {
1275 ast_log(LOG_WARNING, "No channel, no fd?\n");
1280 /* Notify process */
1284 return returnstatus;
1287 static int handle_showagi(int fd, int argc, char *argv[]) {
1288 struct agi_command *e;
1291 return RESULT_SHOWUSAGE;
1293 e = find_command(argv + 2, 1);
1295 ast_cli(fd, e->usage);
1297 if (find_command(argv + 2, -1)) {
1298 return help_workhorse(fd, argv + 1);
1300 join(fullcmd, sizeof(fullcmd), argv+1);
1301 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1305 return help_workhorse(fd, NULL);
1307 return RESULT_SUCCESS;
1310 static int handle_dumpagihtml(int fd, int argc, char *argv[]) {
1311 struct agi_command *e;
1318 return RESULT_SHOWUSAGE;
1320 if (!(htmlfile = fopen(argv[2], "wt"))) {
1321 ast_cli(fd, "Could not create file '%s'\n", argv[2]);
1322 return RESULT_SHOWUSAGE;
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");
1329 fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
1331 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1335 join(fullcmd, sizeof(fullcmd), e->cmda);
1336 /* Hide commands that start with '_' */
1337 if (fullcmd[0] == '_')
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);
1345 tempstr = strsep(&stringp, "\n");
1347 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">%s</TD></TR>\n", tempstr);
1349 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
1350 while ((tempstr = strsep(&stringp, "\n")) != NULL) {
1351 fprintf(htmlfile, "%s<BR>\n",tempstr);
1354 fprintf(htmlfile, "</TD></TR>\n");
1355 fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
1359 fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
1361 ast_cli(fd, "AGI HTML Commands Dumped to: %s\n", argv[2]);
1362 return RESULT_SUCCESS;
1365 static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced)
1368 struct localuser *u;
1376 if (!data || !strlen(data)) {
1377 ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
1382 memset(&agi, 0, sizeof(agi));
1383 strncpy(tmp, data, sizeof(tmp)-1);
1384 strsep(&stringp, "|");
1385 args = strsep(&stringp, "|");
1386 ringy = strsep(&stringp,"|");
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);
1398 if (ast_answer(chan)) {
1399 LOCAL_USER_REMOVE(u);
1404 res = launch_script(tmp, args, fds, enhanced ? &efd : NULL, &pid);
1409 res = run_agi(chan, tmp, &agi, pid);
1415 LOCAL_USER_REMOVE(u);
1419 static int agi_exec(struct ast_channel *chan, void *data)
1421 return agi_exec_full(chan, data, 0);
1424 static int eagi_exec(struct ast_channel *chan, void *data)
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);
1433 res = agi_exec_full(chan, data, 1);
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);
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";
1449 static char dumpagihtml_help[] =
1450 "Usage: dump agihtml <filename>\n"
1451 " Dumps the agi command list in html format to given filename\n";
1453 static struct ast_cli_entry showagi =
1454 { { "show", "agi", NULL }, handle_showagi, "Show AGI commands or specific help", showagi_help };
1456 static struct ast_cli_entry dumpagihtml =
1457 { { "dump", "agihtml", NULL }, handle_dumpagihtml, "Dumps a list of agi command in html format", dumpagihtml_help };
1459 int unload_module(void)
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);
1468 int load_module(void)
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);
1476 char *description(void)
1484 STANDARD_USECOUNT(res);
1490 return ASTERISK_GPL_KEY;