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>
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, (char *)NULL);
156 /* Can't use ast_log since FD's are closed */
157 fprintf(stderr, "Failed to execute '%s': %s\n", script, strerror(errno));
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 : "unknown");
187 fdprintf(fd, "agi_dnid: %s\n", chan->dnid ? chan->dnid : "unknown");
188 fdprintf(fd, "agi_rdnis: %s\n", chan->rdnis ? chan->rdnis : "unknown");
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=-1\n");
408 fdprintf(agi->fd, "200 result=%s\n", data);
410 return RESULT_SUCCESS;
412 return RESULT_FAILURE;
415 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
419 return RESULT_SHOWUSAGE;
420 strncpy(chan->context, argv[2], sizeof(chan->context)-1);
421 fdprintf(agi->fd, "200 result=0\n");
422 return RESULT_SUCCESS;
425 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, char **argv)
428 return RESULT_SHOWUSAGE;
429 strncpy(chan->exten, argv[2], sizeof(chan->exten)-1);
430 fdprintf(agi->fd, "200 result=0\n");
431 return RESULT_SUCCESS;
434 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char **argv)
438 return RESULT_SHOWUSAGE;
439 if (sscanf(argv[2], "%i", &pri) != 1)
440 return RESULT_SHOWUSAGE;
441 chan->priority = pri - 1;
442 fdprintf(agi->fd, "200 result=0\n");
443 return RESULT_SUCCESS;
446 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
448 struct ast_filestream *fs;
450 struct timeval tv, start;
451 long sample_offset = 0;
455 struct ast_dsp *sildet=NULL; /* silence detector dsp */
456 int totalsilence = 0;
458 int silence = 0; /* amount of silence to allow */
459 int gotsilence = 0; /* did we timeout for silence? */
460 char *silencestr=NULL;
464 /* XXX EAGI FIXME XXX */
467 return RESULT_SHOWUSAGE;
468 if (sscanf(argv[5], "%i", &ms) != 1)
469 return RESULT_SHOWUSAGE;
472 silencestr = strchr(argv[6],'s');
473 if ((argc > 7) && (!silencestr))
474 silencestr = strchr(argv[7],'s');
475 if ((argc > 8) && (!silencestr))
476 silencestr = strchr(argv[8],'s');
479 if (strlen(silencestr) > 2) {
480 if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
484 silence = atoi(silencestr);
492 rfmt = chan->readformat;
493 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
495 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
498 sildet = ast_dsp_new();
500 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
503 ast_dsp_set_threshold(sildet, 256);
506 /* backward compatibility, if no offset given, arg[6] would have been
507 * caught below and taken to be a beep, else if it is a digit then it is a
509 if ((argc >6) && (sscanf(argv[6], "%ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
510 res = ast_streamfile(chan, "beep", chan->language);
512 if ((argc > 7) && (!strchr(argv[7], '=')))
513 res = ast_streamfile(chan, "beep", chan->language);
516 res = ast_waitstream(chan, argv[4]);
518 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY, 0, 0644);
521 fdprintf(agi->fd, "200 result=%d (writefile)\n", res);
522 return RESULT_FAILURE;
526 ast_applystream(chan,fs);
527 /* really should have checks */
528 ast_seekstream(fs, sample_offset, SEEK_SET);
531 gettimeofday(&start, NULL);
532 gettimeofday(&tv, NULL);
533 while ((ms < 0) || (((tv.tv_sec - start.tv_sec) * 1000 + (tv.tv_usec - start.tv_usec)/1000) < ms)) {
534 res = ast_waitfor(chan, -1);
537 fdprintf(agi->fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
538 return RESULT_FAILURE;
542 fdprintf(agi->fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
544 return RESULT_FAILURE;
546 switch(f->frametype) {
548 if (strchr(argv[4], f->subclass)) {
549 /* This is an interrupting chracter */
550 sample_offset = ast_tellstream(fs);
551 fdprintf(agi->fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
554 return RESULT_SUCCESS;
557 case AST_FRAME_VOICE:
558 ast_writestream(fs, f);
559 /* this is a safe place to check progress since we know that fs
560 * is valid after a write, and it will then have our current
562 sample_offset = ast_tellstream(fs);
565 ast_dsp_silence(sildet, f, &dspsilence);
567 totalsilence = dspsilence;
571 if (totalsilence > silence) {
572 /* Ended happily with silence */
581 gettimeofday(&tv, NULL);
587 ast_stream_rewind(fs, silence-1000);
590 fdprintf(agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
593 fdprintf(agi->fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
596 res = ast_set_read_format(chan, rfmt);
598 ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
599 ast_dsp_free(sildet);
601 return RESULT_SUCCESS;
604 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
609 return RESULT_SHOWUSAGE;
610 if (sscanf(argv[2], "%d", &timeout) != 1)
611 return RESULT_SHOWUSAGE;
615 chan->whentohangup = time(NULL) + timeout;
617 chan->whentohangup = 0;
618 fdprintf(agi->fd, "200 result=0\n");
619 return RESULT_SUCCESS;
622 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **argv)
624 struct ast_channel *c;
626 /* no argument: hangup the current channel */
627 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
628 fdprintf(agi->fd, "200 result=1\n");
629 return RESULT_SUCCESS;
630 } else if (argc==2) {
631 /* one argument: look for info on the specified channel */
632 c = ast_channel_walk(NULL);
634 if (strcasecmp(argv[1],c->name)==0) {
635 /* we have a matching channel */
636 ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
637 fdprintf(agi->fd, "200 result=1\n");
638 return RESULT_SUCCESS;
640 c = ast_channel_walk(c);
642 /* if we get this far no channel name matched the argument given */
643 fdprintf(agi->fd, "200 result=-1\n");
644 return RESULT_SUCCESS;
646 return RESULT_SHOWUSAGE;
650 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, char **argv)
656 return RESULT_SHOWUSAGE;
658 if (option_verbose > 2)
659 ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
661 app = pbx_findapp(argv[1]);
664 res = pbx_exec(chan, app, argv[2], 1);
666 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
669 fdprintf(agi->fd, "200 result=%d\n", res);
674 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, char **argv)
677 ast_set_callerid(chan, argv[2], 0);
679 /* strncpy(chan->callerid, argv[2], sizeof(chan->callerid)-1);
680 */ fdprintf(agi->fd, "200 result=1\n");
681 return RESULT_SUCCESS;
684 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, char **argv)
686 struct ast_channel *c;
688 /* no argument: supply info on the current channel */
689 fdprintf(agi->fd, "200 result=%d\n", chan->_state);
690 return RESULT_SUCCESS;
691 } else if (argc==3) {
692 /* one argument: look for info on the specified channel */
693 c = ast_channel_walk(NULL);
695 if (strcasecmp(argv[2],c->name)==0) {
696 fdprintf(agi->fd, "200 result=%d\n", c->_state);
697 return RESULT_SUCCESS;
699 c = ast_channel_walk(c);
701 /* if we get this far no channel name matched the argument given */
702 fdprintf(agi->fd, "200 result=-1\n");
703 return RESULT_SUCCESS;
705 return RESULT_SHOWUSAGE;
709 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
712 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
714 fdprintf(agi->fd, "200 result=1\n");
715 return RESULT_SUCCESS;
718 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
722 if ((tempstr = pbx_builtin_getvar_helper(chan, argv[2])) )
723 fdprintf(agi->fd, "200 result=1 (%s)\n", tempstr);
725 fdprintf(agi->fd, "200 result=0\n");
727 return RESULT_SUCCESS;
730 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **argv)
736 return RESULT_SHOWUSAGE;
739 sscanf(argv[2], "%d", &level);
743 prefix = VERBOSE_PREFIX_4;
746 prefix = VERBOSE_PREFIX_3;
749 prefix = VERBOSE_PREFIX_2;
753 prefix = VERBOSE_PREFIX_1;
757 if (level <= option_verbose)
758 ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
760 fdprintf(agi->fd, "200 result=1\n");
762 return RESULT_SUCCESS;
765 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, char **argv)
770 return RESULT_SHOWUSAGE;
771 res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
773 fdprintf(agi->fd, "200 result=0\n");
775 fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
777 return RESULT_SUCCESS;
780 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, char **argv)
784 return RESULT_SHOWUSAGE;
785 res = ast_db_put(argv[2], argv[3], argv[4]);
787 fdprintf(agi->fd, "200 result=0\n");
789 fdprintf(agi->fd, "200 result=1\n");
791 return RESULT_SUCCESS;
794 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, char **argv)
798 return RESULT_SHOWUSAGE;
799 res = ast_db_del(argv[2], argv[3]);
801 fdprintf(agi->fd, "200 result=0\n");
803 fdprintf(agi->fd, "200 result=1\n");
805 return RESULT_SUCCESS;
808 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char **argv)
811 if ((argc < 3) || (argc > 4))
812 return RESULT_SHOWUSAGE;
814 res = ast_db_deltree(argv[2], argv[3]);
816 res = ast_db_deltree(argv[2], NULL);
819 fdprintf(agi->fd, "200 result=0\n");
821 fdprintf(agi->fd, "200 result=1\n");
822 return RESULT_SUCCESS;
825 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
827 fdprintf(agi->fd, "200 result=0\n");
828 return RESULT_SUCCESS;
831 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
833 if (!strncasecmp(argv[2],"on",2)) {
835 ast_moh_start(chan, argv[3]);
837 ast_moh_start(chan, NULL);
839 if (!strncasecmp(argv[2],"off",3)) {
842 fdprintf(agi->fd, "200 result=0\n");
843 return RESULT_SUCCESS;
846 static char usage_setmusic[] =
847 " Usage: SET MUSIC ON <on|off> <class>\n"
848 " Enables/Disables the music on hold generator. If <class> is\n"
849 " not specified then the default music on hold class will be used.\n"
850 " Always returns 0\n";
852 static char usage_dbput[] =
853 " Usage: DATABASE PUT <family> <key> <value>\n"
854 " Adds or updates an entry in the Asterisk database for a\n"
855 " given family, key, and value.\n"
856 " Returns 1 if succesful, 0 otherwise\n";
858 static char usage_dbget[] =
859 " Usage: DATABASE GET <family> <key>\n"
860 " Retrieves an entry in the Asterisk database for a\n"
861 " given family and key.\n"
862 " Returns 0 if <key> is not set. Returns 1 if <key>\n"
863 " is set and returns the variable in parenthesis\n"
864 " example return code: 200 result=1 (testvariable)\n";
866 static char usage_dbdel[] =
867 " Usage: DATABASE DEL <family> <key>\n"
868 " Deletes an entry in the Asterisk database for a\n"
869 " given family and key.\n"
870 " Returns 1 if succesful, 0 otherwise\n";
872 static char usage_dbdeltree[] =
873 " Usage: DATABASE DELTREE <family> [keytree]\n"
874 " Deletes a family or specific keytree withing a family\n"
875 " in the Asterisk database.\n"
876 " Returns 1 if succesful, 0 otherwise\n";
878 static char usage_verbose[] =
879 " Usage: VERBOSE <message> <level>\n"
880 " Sends <message> to the console via verbose message system.\n"
881 " <level> is the the verbose level (1-4)\n"
882 " Always returns 1\n";
884 static char usage_getvariable[] =
885 " Usage: GET VARIABLE <variablename>\n"
886 " Returns 0 if <variablename> is not set. Returns 1 if <variablename>\n"
887 " is set and returns the variable in parenthesis\n"
888 " example return code: 200 result=1 (testvariable)\n";
890 static char usage_setvariable[] =
891 " Usage: SET VARIABLE <variablename> <value>\n";
893 static char usage_channelstatus[] =
894 " Usage: CHANNEL STATUS [<channelname>]\n"
895 " Returns the status of the specified channel.\n"
896 " If no channel name is given the returns the status of the\n"
897 " current channel.\n"
899 " 0 Channel is down and available\n"
900 " 1 Channel is down, but reserved\n"
901 " 2 Channel is off hook\n"
902 " 3 Digits (or equivalent) have been dialed\n"
903 " 4 Line is ringing\n"
904 " 5 Remote end is ringing\n"
908 static char usage_setcallerid[] =
909 " Usage: SET CALLERID <number>\n"
910 " Changes the callerid of the current channel.\n";
912 static char usage_exec[] =
913 " Usage: EXEC <application> <options>\n"
914 " Executes <application> with given <options>.\n"
915 " Returns whatever the application returns, or -2 on failure to find application\n";
917 static char usage_hangup[] =
918 " Usage: HANGUP [<channelname>]\n"
919 " Hangs up the specified channel.\n"
920 " If no channel name is given, hangs up the current channel\n";
922 static char usage_answer[] =
924 " Answers channel if not already in answer state. Returns -1 on\n"
925 " channel failure, or 0 if successful.\n";
927 static char usage_waitfordigit[] =
928 " Usage: WAIT FOR DIGIT <timeout>\n"
929 " Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
930 " Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
931 " the numerical value of the ascii of the digit if one is received. Use -1\n"
932 " for the timeout value if you desire the call to block indefinitely.\n";
934 static char usage_sendtext[] =
935 " Usage: SEND TEXT \"<text to send>\"\n"
936 " Sends the given text on a channel. Most channels do not support the\n"
937 " transmission of text. Returns 0 if text is sent, or if the channel does not\n"
938 " support text transmission. Returns -1 only on error/hangup. Text\n"
939 " consisting of greater than one word should be placed in quotes since the\n"
940 " command only accepts a single argument.\n";
942 static char usage_recvchar[] =
943 " Usage: RECEIVE CHAR <timeout>\n"
944 " Receives a character of text on a channel. Specify timeout to be the\n"
945 " maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
946 " do not support the reception of text. Returns the decimal value of the character\n"
947 " if one is received, or 0 if the channel does not support text reception. Returns\n"
948 " -1 only on error/hangup.\n";
950 static char usage_tddmode[] =
951 " Usage: TDD MODE <on|off>\n"
952 " Enable/Disable TDD transmission/reception on a channel. Returns 1 if\n"
953 " successful, or 0 if channel is not TDD-capable.\n";
955 static char usage_sendimage[] =
956 " Usage: SEND IMAGE <image>\n"
957 " Sends the given image on a channel. Most channels do not support the\n"
958 " transmission of images. Returns 0 if image is sent, or if the channel does not\n"
959 " support image transmission. Returns -1 only on error/hangup. Image names\n"
960 " should not include extensions.\n";
962 static char usage_streamfile[] =
963 " Usage: STREAM FILE <filename> <escape digits> [sample offset]\n"
964 " Send the given file, allowing playback to be interrupted by the given\n"
965 " digits, if any. Use double quotes for the digits if you wish none to be\n"
966 " permitted. If sample offset is provided then the audio will seek to sample\n"
967 " offset before play starts. Returns 0 if playback completes without a digit\n"
968 " being pressed, or the ASCII numerical value of the digit if one was pressed,\n"
969 " or -1 on error or if the channel was disconnected. Remember, the file\n"
970 " extension must not be included in the filename.\n";
972 static char usage_saynumber[] =
973 " Usage: SAY NUMBER <number> <escape digits>\n"
974 " Say a given number, returning early if any of the given DTMF digits\n"
975 " are received on the channel. Returns 0 if playback completes without a digit\n"
976 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
977 " -1 on error/hangup.\n";
979 static char usage_saydigits[] =
980 " Usage: SAY DIGITS <number> <escape digits>\n"
981 " Say a given digit string, returning early if any of the given DTMF digits\n"
982 " are received on the channel. Returns 0 if playback completes without a digit\n"
983 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
984 " -1 on error/hangup.\n";
986 static char usage_getdata[] =
987 " Usage: GET DATA <file to be streamed> [timeout] [max digits]\n"
988 " Stream the given file, and recieve DTMF data. Returns the digits recieved\n"
989 "from the channel at the other end.\n";
991 static char usage_setcontext[] =
992 " Usage: SET CONTEXT <desired context>\n"
993 " Sets the context for continuation upon exiting the application.\n";
995 static char usage_setextension[] =
996 " Usage: SET EXTENSION <new extension>\n"
997 " Changes the extension for continuation upon exiting the application.\n";
999 static char usage_setpriority[] =
1000 " Usage: SET PRIORITY <num>\n"
1001 " Changes the priority for continuation upon exiting the application.\n";
1003 static char usage_recordfile[] =
1004 " Usage: RECORD FILE <filename> <format> <escape digits> <timeout> [offset samples] [BEEP] [s=silence]\n"
1005 " Record to a file until a given dtmf digit in the sequence is received\n"
1006 " Returns -1 on hangup or error. The format will specify what kind of file\n"
1007 " will be recorded. The timeout is the maximum record time in milliseconds, or\n"
1008 " -1 for no timeout. Offset samples is optional, and if provided will seek to\n"
1009 " the offset without exceeding the end of the file. \"silence\" is the number\n"
1010 " of seconds of silence allowed before the function returns despite the\n"
1011 " lack of dtmf digits or reaching timeout. Silence value must be\n"
1012 " preceeded by \"s=\" and is optional.\n";
1015 static char usage_autohangup[] =
1016 " Usage: SET AUTOHANGUP <time>\n"
1017 " Cause the channel to automatically hangup at <time> seconds in the\n"
1018 "future. Of course it can be hungup before then as well. Setting to\n"
1019 "0 will cause the autohangup feature to be disabled on this channel.\n";
1021 static char usage_noop[] =
1025 static agi_command commands[] = {
1026 { { "answer", NULL }, handle_answer, "Asserts answer", usage_answer },
1027 { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
1028 { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
1029 { { "receive", "char", NULL }, handle_recvchar, "Receives text from channels supporting it", usage_recvchar },
1030 { { "tdd", "mode", NULL }, handle_tddmode, "Sends text to channels supporting it", usage_tddmode },
1031 { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
1032 { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
1033 { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
1034 { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
1035 { { "get", "data", NULL }, handle_getdata, "Gets data on a channel", usage_getdata },
1036 { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
1037 { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
1038 { { "set", "priority", NULL }, handle_setpriority, "Prioritizes the channel", usage_setpriority },
1039 { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
1040 { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
1041 { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
1042 { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
1043 { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
1044 { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus },
1045 { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable },
1046 { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable },
1047 { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose },
1048 { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget },
1049 { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput },
1050 { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel },
1051 { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree },
1052 { { "noop", NULL }, handle_noop, "Does nothing", usage_noop },
1053 { { "set", "music", NULL }, handle_setmusic, "Enable/Disable Music on hold generator", usage_setmusic }
1056 static void join(char *s, int len, char *w[])
1059 /* Join words into a string */
1061 for (x=0;w[x];x++) {
1063 strncat(s, " ", len - strlen(s));
1064 strncat(s, w[x], len - strlen(s));
1068 static int help_workhorse(int fd, char *match[])
1073 struct agi_command *e;
1075 join(matchstr, sizeof(matchstr), match);
1076 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1079 join(fullcmd, sizeof(fullcmd), e->cmda);
1080 /* Hide commands that start with '_' */
1081 if (fullcmd[0] == '_')
1084 if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1088 ast_cli(fd, "%20.20s %s\n", fullcmd, e->summary);
1093 static agi_command *find_command(char *cmds[], int exact)
1098 for (x=0;x < sizeof(commands) / sizeof(commands[0]);x++) {
1099 /* start optimistic */
1101 for (y=0;match && cmds[y]; y++) {
1102 /* If there are no more words in the command (and we're looking for
1103 an exact match) or there is a difference between the two words,
1104 then this is not a match */
1105 if (!commands[x].cmda[y] && !exact)
1107 /* don't segfault if the next part of a command doesn't exist */
1108 if (!commands[x].cmda[y]) return NULL;
1109 if (strcasecmp(commands[x].cmda[y], cmds[y]))
1112 /* If more words are needed to complete the command then this is not
1113 a candidate (unless we're looking for a really inexact answer */
1114 if ((exact > -1) && commands[x].cmda[y])
1117 return &commands[x];
1123 static int parse_args(char *s, int *max, char *argv[])
1135 /* If it's escaped, put a literal quote */
1140 if (quoted && whitespace) {
1141 /* If we're starting a quote, coming off white space start a new word, too */
1149 if (!quoted && !escaped) {
1150 /* If we're not quoted, mark this as whitespace, and
1151 end the previous argument */
1155 /* Otherwise, just treat it as anything else */
1159 /* If we're escaped, print a literal, otherwise enable escaping */
1169 if (x >= MAX_ARGS -1) {
1170 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1173 /* Coming off of whitespace, start the next argument */
1182 /* Null terminate */
1189 static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf)
1191 char *argv[MAX_ARGS];
1196 parse_args(buf, &argc, argv);
1199 for (x=0;x<argc;x++)
1200 fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
1202 c = find_command(argv, 0);
1204 res = c->handler(chan, agi, argc, argv);
1206 case RESULT_SHOWUSAGE:
1207 fdprintf(agi->fd, "520-Invalid command syntax. Proper usage follows:\n");
1208 fdprintf(agi->fd, c->usage);
1209 fdprintf(agi->fd, "520 End of proper usage.\n");
1211 case RESULT_FAILURE:
1212 /* They've already given the failure. We've been hung up on so handle this
1217 fdprintf(agi->fd, "510 Invalid or unknown command\n");
1222 static int run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid)
1224 struct ast_channel *c;
1227 int returnstatus = 0;
1228 struct ast_frame *f;
1231 if (!(readf = fdopen(agi->ctrl, "r"))) {
1232 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
1237 setup_env(chan, request, agi->fd, (agi->audio > -1));
1240 c = ast_waitfor_nandfds(&chan, 1, &agi->ctrl, 1, NULL, &outfd, &ms);
1242 /* Idle the channel until we get a command */
1245 ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
1249 /* If it's voice, write it to the audio pipe */
1250 if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
1251 /* Write, ignoring errors */
1252 write(agi->audio, f->data, f->datalen);
1256 } else if (outfd > -1) {
1257 if (!fgets(buf, sizeof(buf), readf)) {
1258 /* Program terminated */
1261 if (option_verbose > 2)
1262 ast_verbose(VERBOSE_PREFIX_3 "AGI Script %s completed, returning %d\n", request, returnstatus);
1263 /* No need to kill the pid anymore, since they closed us */
1267 /* get rid of trailing newline, if any */
1268 if (*buf && buf[strlen(buf) - 1] == '\n')
1269 buf[strlen(buf) - 1] = 0;
1271 returnstatus |= agi_handle_command(chan, agi, buf);
1272 /* If the handle_command returns -1, we need to stop */
1273 if (returnstatus < 0) {
1277 ast_log(LOG_WARNING, "No channel, no fd?\n");
1282 /* Notify process */
1286 return returnstatus;
1289 static int handle_showagi(int fd, int argc, char *argv[]) {
1290 struct agi_command *e;
1293 return RESULT_SHOWUSAGE;
1295 e = find_command(argv + 2, 1);
1297 ast_cli(fd, e->usage);
1299 if (find_command(argv + 2, -1)) {
1300 return help_workhorse(fd, argv + 1);
1302 join(fullcmd, sizeof(fullcmd), argv+1);
1303 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1307 return help_workhorse(fd, NULL);
1309 return RESULT_SUCCESS;
1312 static int handle_dumpagihtml(int fd, int argc, char *argv[]) {
1313 struct agi_command *e;
1320 return RESULT_SHOWUSAGE;
1322 if (!(htmlfile = fopen(argv[2], "wt"))) {
1323 ast_cli(fd, "Could not create file '%s'\n", argv[2]);
1324 return RESULT_SHOWUSAGE;
1327 fprintf(htmlfile, "<HTML>\n<HEAD>\n<TITLE>AGI Commands</TITLE>\n</HEAD>\n");
1328 fprintf(htmlfile, "<BODY>\n<CENTER><B><H1>AGI Commands</H1></B></CENTER>\n\n");
1331 fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
1333 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1337 join(fullcmd, sizeof(fullcmd), e->cmda);
1338 /* Hide commands that start with '_' */
1339 if (fullcmd[0] == '_')
1342 fprintf(htmlfile, "<TR><TD><TABLE BORDER=\"1\" CELLPADDING=\"5\" WIDTH=\"100%%\">\n");
1343 fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TD></TR>\n", fullcmd,e->summary);
1347 tempstr = strsep(&stringp, "\n");
1349 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">%s</TD></TR>\n", tempstr);
1351 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
1352 while ((tempstr = strsep(&stringp, "\n")) != NULL) {
1353 fprintf(htmlfile, "%s<BR>\n",tempstr);
1356 fprintf(htmlfile, "</TD></TR>\n");
1357 fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
1361 fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
1363 ast_cli(fd, "AGI HTML Commands Dumped to: %s\n", argv[2]);
1364 return RESULT_SUCCESS;
1367 static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced)
1370 struct localuser *u;
1378 if (!data || !strlen(data)) {
1379 ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
1384 memset(&agi, 0, sizeof(agi));
1385 strncpy(tmp, data, sizeof(tmp)-1);
1386 strsep(&stringp, "|");
1387 args = strsep(&stringp, "|");
1388 ringy = strsep(&stringp,"|");
1393 /* Answer if need be */
1394 if (chan->_state != AST_STATE_UP) {
1395 if (ringy) { /* if for ringing first */
1396 /* a little ringy-dingy first */
1397 ast_indicate(chan, AST_CONTROL_RINGING);
1400 if (ast_answer(chan)) {
1401 LOCAL_USER_REMOVE(u);
1406 res = launch_script(tmp, args, fds, enhanced ? &efd : NULL, &pid);
1411 res = run_agi(chan, tmp, &agi, pid);
1417 LOCAL_USER_REMOVE(u);
1421 static int agi_exec(struct ast_channel *chan, void *data)
1423 return agi_exec_full(chan, data, 0);
1426 static int eagi_exec(struct ast_channel *chan, void *data)
1430 readformat = chan->readformat;
1431 if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
1432 ast_log(LOG_WARNING, "Unable to set channel '%s' to linear mode\n", chan->name);
1435 res = agi_exec_full(chan, data, 1);
1437 if (ast_set_read_format(chan, readformat)) {
1438 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %s\n", chan->name, ast_getformatname(readformat));
1444 static char showagi_help[] =
1445 "Usage: show agi [topic]\n"
1446 " When called with a topic as an argument, displays usage\n"
1447 " information on the given command. If called without a\n"
1448 " topic, it provides a list of AGI commands.\n";
1451 static char dumpagihtml_help[] =
1452 "Usage: dump agihtml <filename>\n"
1453 " Dumps the agi command list in html format to given filename\n";
1455 static struct ast_cli_entry showagi =
1456 { { "show", "agi", NULL }, handle_showagi, "Show AGI commands or specific help", showagi_help };
1458 static struct ast_cli_entry dumpagihtml =
1459 { { "dump", "agihtml", NULL }, handle_dumpagihtml, "Dumps a list of agi command in html format", dumpagihtml_help };
1461 int unload_module(void)
1463 STANDARD_HANGUP_LOCALUSERS;
1464 ast_cli_unregister(&showagi);
1465 ast_cli_unregister(&dumpagihtml);
1466 ast_unregister_application(eapp);
1467 return ast_unregister_application(app);
1470 int load_module(void)
1472 ast_cli_register(&showagi);
1473 ast_cli_register(&dumpagihtml);
1474 ast_register_application(eapp, eagi_exec, synopsis, descrip);
1475 return ast_register_application(app, agi_exec, synopsis, descrip);
1478 char *description(void)
1486 STANDARD_USECOUNT(res);
1492 return ASTERISK_GPL_KEY;