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.h"
38 #include "../astconf.h"
44 /* Recycle some stuff from the CLI interface */
45 #define fdprintf ast_cli
47 typedef struct agi_state {
48 int fd; /* FD for general output */
49 int audio; /* FD for audio output */
50 int ctrl; /* FD for input control */
53 typedef struct agi_command {
54 /* Null terminated list of the words of the command */
55 char *cmda[AST_MAX_CMD_LEN];
56 /* Handler for the command (channel, AGI state, # of arguments, argument list).
57 Returns RESULT_SHOWUSAGE for improper arguments */
58 int (*handler)(struct ast_channel *chan, AGI *agi, int argc, char *argv[]);
59 /* Summary of the command (< 60 characters) */
61 /* Detailed usage information */
65 static char *tdesc = "Asterisk Gateway Interface (AGI)";
67 static char *app = "AGI";
69 static char *eapp = "EAGI";
71 static char *synopsis = "Executes an AGI compliant application";
73 static char *descrip =
74 " [E]AGI(command|args): Executes an Asterisk Gateway Interface compliant\n"
75 "program on a channel. AGI allows Asterisk to launch external programs\n"
76 "written in any language to control a telephony channel, play audio,\n"
77 "read DTMF digits, etc. by communicating with the AGI protocol on stdin\n"
78 "and stdout. Returns -1 on hangup or if application requested hangup, or\n"
79 "0 on non-hangup exit. Using 'EAGI' provides enhanced AGI, with audio\n"
80 "available out of band on file descriptor 3\n";
87 #define TONE_BLOCK_SIZE 200
89 static int launch_script(char *script, char *args, int *fds, int *efd, int *opid)
98 if (script[0] != '/') {
99 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_AGI_DIR, script);
103 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
107 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
114 ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
121 res = fcntl(audio[1], F_GETFL);
123 res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
125 ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
137 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
141 /* Redirect stdin and out, provide enhanced audio channel if desired */
142 dup2(fromast[0], STDIN_FILENO);
143 dup2(toast[1], STDOUT_FILENO);
145 dup2(audio[0], STDERR_FILENO + 1);
147 close(STDERR_FILENO + 1);
149 /* Close everything but stdin/out/error */
150 for (x=STDERR_FILENO + 2;x<1024;x++)
153 execl(script, script, args, NULL);
154 /* Can't use ast_log since FD's are closed */
155 fprintf(stderr, "Failed to execute '%s': %s\n", script, strerror(errno));
158 if (option_verbose > 2)
159 ast_verbose(VERBOSE_PREFIX_3 "Launched AGI Script %s\n", script);
165 /* close what we're not using in the parent */
173 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced)
175 /* Print initial environment, with agi_request always being the first
177 fdprintf(fd, "agi_request: %s\n", request);
178 fdprintf(fd, "agi_channel: %s\n", chan->name);
179 fdprintf(fd, "agi_language: %s\n", chan->language);
180 fdprintf(fd, "agi_type: %s\n", chan->type);
183 fdprintf(fd, "agi_callerid: %s\n", chan->callerid ? chan->callerid : "");
184 fdprintf(fd, "agi_dnid: %s\n", chan->dnid ? chan->dnid : "");
185 fdprintf(fd, "agi_rdnis: %s\n", chan->rdnis ? chan->rdnis : "");
187 /* Context information */
188 fdprintf(fd, "agi_context: %s\n", chan->context);
189 fdprintf(fd, "agi_extension: %s\n", chan->exten);
190 fdprintf(fd, "agi_priority: %d\n", chan->priority);
191 fdprintf(fd, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
193 /* End with empty return */
197 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
201 if (chan->_state != AST_STATE_UP) {
202 /* Answer the chan */
203 res = ast_answer(chan);
205 fdprintf(agi->fd, "200 result=%d\n", res);
207 return RESULT_SUCCESS;
209 return RESULT_FAILURE;
212 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
217 return RESULT_SHOWUSAGE;
218 if (sscanf(argv[3], "%i", &to) != 1)
219 return RESULT_SHOWUSAGE;
220 res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
221 fdprintf(agi->fd, "200 result=%d\n", res);
223 return RESULT_SUCCESS;
225 return RESULT_FAILURE;
228 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
232 return RESULT_SHOWUSAGE;
233 /* At the moment, the parser (perhaps broken) returns with
234 the last argument PLUS the newline at the end of the input
235 buffer. This probably needs to be fixed, but I wont do that
236 because other stuff may break as a result. The right way
237 would probably be to strip off the trailing newline before
238 parsing, then here, add a newline at the end of the string
239 before sending it to ast_sendtext --DUDE */
240 res = ast_sendtext(chan, argv[2]);
241 fdprintf(agi->fd, "200 result=%d\n", res);
243 return RESULT_SUCCESS;
245 return RESULT_FAILURE;
248 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
252 return RESULT_SHOWUSAGE;
253 res = ast_recvchar(chan,atoi(argv[2]));
255 fdprintf(agi->fd, "200 result=%d (timeout)\n", res);
256 return RESULT_SUCCESS;
259 fdprintf(agi->fd, "200 result=%d\n", res);
260 return RESULT_SUCCESS;
263 fdprintf(agi->fd, "200 result=%d (hangup)\n", res);
264 return RESULT_FAILURE;
268 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
272 return RESULT_SHOWUSAGE;
273 if (!strncasecmp(argv[2],"on",2)) x = 1; else x = 0;
274 if (!strncasecmp(argv[2],"mate",4)) x = 2;
275 if (!strncasecmp(argv[2],"tdd",3)) x = 1;
276 res = ast_channel_setoption(chan,AST_OPTION_TDD,&x,sizeof(char),0);
277 fdprintf(agi->fd, "200 result=%d\n", res);
279 return RESULT_SUCCESS;
281 return RESULT_FAILURE;
284 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
288 return RESULT_SHOWUSAGE;
289 res = ast_send_image(chan, argv[2]);
290 if (!ast_check_hangup(chan))
292 fdprintf(agi->fd, "200 result=%d\n", res);
294 return RESULT_SUCCESS;
296 return RESULT_FAILURE;
299 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
302 struct ast_filestream *fs;
303 long sample_offset = 0;
307 return RESULT_SHOWUSAGE;
309 return RESULT_SHOWUSAGE;
310 if ((argc > 4) && (sscanf(argv[4], "%ld", &sample_offset) != 1))
311 return RESULT_SHOWUSAGE;
313 fs = ast_openstream(chan, argv[2], chan->language);
315 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
316 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
317 return RESULT_FAILURE;
319 ast_seekstream(fs, 0, SEEK_END);
320 max_length = ast_tellstream(fs);
321 ast_seekstream(fs, sample_offset, SEEK_SET);
322 res = ast_applystream(chan, fs);
323 res = ast_playstream(fs);
325 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
327 return RESULT_SHOWUSAGE;
329 return RESULT_FAILURE;
331 res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
332 /* this is to check for if ast_waitstream closed the stream, we probably are at
333 * the end of the stream, return that amount, else check for the amount */
334 sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
335 ast_stopstream(chan);
337 /* Stop this command, don't print a result line, as there is a new command */
338 return RESULT_SUCCESS;
340 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
342 return RESULT_SUCCESS;
344 return RESULT_FAILURE;
347 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
352 return RESULT_SHOWUSAGE;
353 if (sscanf(argv[2], "%i", &num) != 1)
354 return RESULT_SHOWUSAGE;
355 res = ast_say_number_full(chan, num, argv[3], chan->language, agi->audio, agi->ctrl);
357 return RESULT_SUCCESS;
358 fdprintf(agi->fd, "200 result=%d\n", res);
360 return RESULT_SUCCESS;
362 return RESULT_FAILURE;
365 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
370 return RESULT_SHOWUSAGE;
371 if (sscanf(argv[2], "%i", &num) != 1)
372 return RESULT_SHOWUSAGE;
373 res = ast_say_digit_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
374 if (res == 1) /* New command */
375 return RESULT_SUCCESS;
376 fdprintf(agi->fd, "200 result=%d\n", res);
378 return RESULT_SUCCESS;
380 return RESULT_FAILURE;
383 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
391 return RESULT_SHOWUSAGE;
392 if (argc >= 4) timeout = atoi(argv[3]); else timeout = 0;
393 if (argc >= 5) max = atoi(argv[4]); else max = 1024;
394 res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
395 if (res == 2) /* New command */
396 return RESULT_SUCCESS;
398 fdprintf(agi->fd, "200 result=%s (timeout)\n", data);
400 fdprintf(agi->fd, "200 result=%s\n", data);
402 return RESULT_SUCCESS;
404 return RESULT_FAILURE;
407 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
411 return RESULT_SHOWUSAGE;
412 strncpy(chan->context, argv[2], sizeof(chan->context)-1);
413 fdprintf(agi->fd, "200 result=0\n");
414 return RESULT_SUCCESS;
417 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, char **argv)
420 return RESULT_SHOWUSAGE;
421 strncpy(chan->exten, argv[2], sizeof(chan->exten)-1);
422 fdprintf(agi->fd, "200 result=0\n");
423 return RESULT_SUCCESS;
426 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char **argv)
430 return RESULT_SHOWUSAGE;
431 if (sscanf(argv[2], "%i", &pri) != 1)
432 return RESULT_SHOWUSAGE;
433 chan->priority = pri - 1;
434 fdprintf(agi->fd, "200 result=0\n");
435 return RESULT_SUCCESS;
438 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
440 struct ast_filestream *fs;
442 struct timeval tv, start;
443 long sample_offset = 0;
447 /* XXX EAGI FIXME XXX */
450 return RESULT_SHOWUSAGE;
451 if (sscanf(argv[5], "%i", &ms) != 1)
452 return RESULT_SHOWUSAGE;
453 /* backward compatibility, if no offset given, arg[6] would have been
454 * caught below and taken to be a beep, else if it is a digit then it is a
456 if ((argc >6) && (sscanf(argv[6], "%ld", &sample_offset) != 1))
457 res = ast_streamfile(chan, "beep", chan->language);
460 res = ast_streamfile(chan, "beep", chan->language);
462 res = ast_waitstream(chan, argv[4]);
464 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY, 0, 0644);
467 fdprintf(agi->fd, "200 result=%d (writefile)\n", res);
468 return RESULT_FAILURE;
472 ast_applystream(chan,fs);
473 /* really should have checks */
474 ast_seekstream(fs, sample_offset, SEEK_SET);
477 gettimeofday(&start, NULL);
478 gettimeofday(&tv, NULL);
479 while ((ms < 0) || (((tv.tv_sec - start.tv_sec) * 1000 + (tv.tv_usec - start.tv_usec)/1000) < ms)) {
480 res = ast_waitfor(chan, -1);
483 fdprintf(agi->fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
484 return RESULT_FAILURE;
488 fdprintf(agi->fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
490 return RESULT_FAILURE;
492 switch(f->frametype) {
494 if (strchr(argv[4], f->subclass)) {
495 /* This is an interrupting chracter */
496 sample_offset = ast_tellstream(fs);
497 fdprintf(agi->fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
500 return RESULT_SUCCESS;
503 case AST_FRAME_VOICE:
504 ast_writestream(fs, f);
505 /* this is a safe place to check progress since we know that fs
506 * is valid after a write, and it will then have our current
508 sample_offset = ast_tellstream(fs);
512 gettimeofday(&tv, NULL);
514 fdprintf(agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
517 fdprintf(agi->fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
518 return RESULT_SUCCESS;
521 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
526 return RESULT_SHOWUSAGE;
527 if (sscanf(argv[2], "%d", &timeout) != 1)
528 return RESULT_SHOWUSAGE;
532 chan->whentohangup = time(NULL) + timeout;
534 chan->whentohangup = 0;
535 fdprintf(agi->fd, "200 result=0\n");
536 return RESULT_SUCCESS;
539 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **argv)
541 struct ast_channel *c;
543 /* no argument: hangup the current channel */
544 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
545 fdprintf(agi->fd, "200 result=1\n");
546 return RESULT_SUCCESS;
547 } else if (argc==2) {
548 /* one argument: look for info on the specified channel */
549 c = ast_channel_walk(NULL);
551 if (strcasecmp(argv[1],c->name)==0) {
552 /* we have a matching channel */
553 ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
554 fdprintf(agi->fd, "200 result=1\n");
555 return RESULT_SUCCESS;
557 c = ast_channel_walk(c);
559 /* if we get this far no channel name matched the argument given */
560 fdprintf(agi->fd, "200 result=-1\n");
561 return RESULT_SUCCESS;
563 return RESULT_SHOWUSAGE;
567 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, char **argv)
573 return RESULT_SHOWUSAGE;
575 if (option_verbose > 2)
576 ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
578 app = pbx_findapp(argv[1]);
581 res = pbx_exec(chan, app, argv[2], 1);
583 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
586 fdprintf(agi->fd, "200 result=%d\n", res);
591 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, char **argv)
594 ast_set_callerid(chan, argv[2], 0);
596 /* strncpy(chan->callerid, argv[2], sizeof(chan->callerid)-1);
597 */ fdprintf(agi->fd, "200 result=1\n");
598 return RESULT_SUCCESS;
601 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, char **argv)
603 struct ast_channel *c;
605 /* no argument: supply info on the current channel */
606 fdprintf(agi->fd, "200 result=%d\n", chan->_state);
607 return RESULT_SUCCESS;
608 } else if (argc==3) {
609 /* one argument: look for info on the specified channel */
610 c = ast_channel_walk(NULL);
612 if (strcasecmp(argv[2],c->name)==0) {
613 fdprintf(agi->fd, "200 result=%d\n", c->_state);
614 return RESULT_SUCCESS;
616 c = ast_channel_walk(c);
618 /* if we get this far no channel name matched the argument given */
619 fdprintf(agi->fd, "200 result=-1\n");
620 return RESULT_SUCCESS;
622 return RESULT_SHOWUSAGE;
626 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
629 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
631 fdprintf(agi->fd, "200 result=1\n");
632 return RESULT_SUCCESS;
635 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
639 if ((tempstr = pbx_builtin_getvar_helper(chan, argv[2])) )
640 fdprintf(agi->fd, "200 result=1 (%s)\n", tempstr);
642 fdprintf(agi->fd, "200 result=0\n");
644 return RESULT_SUCCESS;
647 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **argv)
653 return RESULT_SHOWUSAGE;
656 sscanf(argv[2], "%d", &level);
660 prefix = VERBOSE_PREFIX_4;
663 prefix = VERBOSE_PREFIX_3;
666 prefix = VERBOSE_PREFIX_2;
670 prefix = VERBOSE_PREFIX_1;
674 if (level <= option_verbose)
675 ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
677 fdprintf(agi->fd, "200 result=1\n");
679 return RESULT_SUCCESS;
682 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, char **argv)
687 return RESULT_SHOWUSAGE;
688 res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
690 fdprintf(agi->fd, "200 result=0\n");
692 fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
694 return RESULT_SUCCESS;
697 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, char **argv)
701 return RESULT_SHOWUSAGE;
702 res = ast_db_put(argv[2], argv[3], argv[4]);
704 fdprintf(agi->fd, "200 result=0\n");
706 fdprintf(agi->fd, "200 result=1\n");
708 return RESULT_SUCCESS;
711 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, char **argv)
715 return RESULT_SHOWUSAGE;
716 res = ast_db_del(argv[2], argv[3]);
718 fdprintf(agi->fd, "200 result=0\n");
720 fdprintf(agi->fd, "200 result=1\n");
722 return RESULT_SUCCESS;
725 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char **argv)
728 if ((argc < 3) || (argc > 4))
729 return RESULT_SHOWUSAGE;
731 res = ast_db_deltree(argv[2], argv[3]);
733 res = ast_db_deltree(argv[2], NULL);
736 fdprintf(agi->fd, "200 result=0\n");
738 fdprintf(agi->fd, "200 result=1\n");
739 return RESULT_SUCCESS;
742 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
744 fdprintf(agi->fd, "200 result=0\n");
745 return RESULT_SUCCESS;
748 static char usage_dbput[] =
749 " Usage: DATABASE PUT <family> <key> <value>\n"
750 " Adds or updates an entry in the Asterisk database for a\n"
751 " given family, key, and value.\n"
752 " Returns 1 if succesful, 0 otherwise\n";
754 static char usage_dbget[] =
755 " Usage: DATABASE GET <family> <key>\n"
756 " Retrieves an entry in the Asterisk database for a\n"
757 " given family and key.\n"
758 " Returns 0 if <key> is not set. Returns 1 if <key>\n"
759 " is set and returns the variable in parenthesis\n"
760 " example return code: 200 result=1 (testvariable)\n";
762 static char usage_dbdel[] =
763 " Usage: DATABASE DEL <family> <key>\n"
764 " Deletes an entry in the Asterisk database for a\n"
765 " given family and key.\n"
766 " Returns 1 if succesful, 0 otherwise\n";
768 static char usage_dbdeltree[] =
769 " Usage: DATABASE DELTREE <family> [keytree]\n"
770 " Deletes a family or specific keytree withing a family\n"
771 " in the Asterisk database.\n"
772 " Returns 1 if succesful, 0 otherwise\n";
774 static char usage_verbose[] =
775 " Usage: VERBOSE <message> <level>\n"
776 " Sends <message> to the console via verbose message system.\n"
777 " <level> is the the verbose level (1-4)\n"
778 " Always returns 1\n";
780 static char usage_getvariable[] =
781 " Usage: GET VARIABLE <variablename>\n"
782 " Returns 0 if <variablename> is not set. Returns 1 if <variablename>\n"
783 " is set and returns the variable in parenthesis\n"
784 " example return code: 200 result=1 (testvariable)\n";
786 static char usage_setvariable[] =
787 " Usage: SET VARIABLE <variablename> <value>\n";
789 static char usage_channelstatus[] =
790 " Usage: CHANNEL STATUS [<channelname>]\n"
791 " Returns the status of the specified channel.\n"
792 " If no channel name is given the returns the status of the\n"
793 " current channel.\n"
795 " 0 Channel is down and available\n"
796 " 1 Channel is down, but reserved\n"
797 " 2 Channel is off hook\n"
798 " 3 Digits (or equivalent) have been dialed\n"
799 " 4 Line is ringing\n"
800 " 5 Remote end is ringing\n"
804 static char usage_setcallerid[] =
805 " Usage: SET CALLERID <number>\n"
806 " Changes the callerid of the current channel.\n";
808 static char usage_exec[] =
809 " Usage: EXEC <application> <options>\n"
810 " Executes <application> with given <options>.\n"
811 " Returns whatever the application returns, or -2 on failure to find application\n";
813 static char usage_hangup[] =
814 " Usage: HANGUP [<channelname>]\n"
815 " Hangs up the specified channel.\n"
816 " If no channel name is given, hangs up the current channel\n";
818 static char usage_answer[] =
820 " Answers channel if not already in answer state. Returns -1 on\n"
821 " channel failure, or 0 if successful.\n";
823 static char usage_waitfordigit[] =
824 " Usage: WAIT FOR DIGIT <timeout>\n"
825 " Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
826 " Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
827 " the numerical value of the ascii of the digit if one is received. Use -1\n"
828 " for the timeout value if you desire the call to block indefinitely.\n";
830 static char usage_sendtext[] =
831 " Usage: SEND TEXT \"<text to send>\"\n"
832 " Sends the given text on a channel. Most channels do not support the\n"
833 " transmission of text. Returns 0 if text is sent, or if the channel does not\n"
834 " support text transmission. Returns -1 only on error/hangup. Text\n"
835 " consisting of greater than one word should be placed in quotes since the\n"
836 " command only accepts a single argument.\n";
838 static char usage_recvchar[] =
839 " Usage: RECEIVE CHAR <timeout>\n"
840 " Receives a character of text on a channel. Specify timeout to be the\n"
841 " maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
842 " do not support the reception of text. Returns the decimal value of the character\n"
843 " if one is received, or 0 if the channel does not support text reception. Returns\n"
844 " -1 only on error/hangup.\n";
846 static char usage_tddmode[] =
847 " Usage: TDD MODE <on|off>\n"
848 " Enable/Disable TDD transmission/reception on a channel. Returns 1 if\n"
849 " successful, or 0 if channel is not TDD-capable.\n";
851 static char usage_sendimage[] =
852 " Usage: SEND IMAGE <image>\n"
853 " Sends the given image on a channel. Most channels do not support the\n"
854 " transmission of images. Returns 0 if image is sent, or if the channel does not\n"
855 " support image transmission. Returns -1 only on error/hangup. Image names\n"
856 " should not include extensions.\n";
858 static char usage_streamfile[] =
859 " Usage: STREAM FILE <filename> <escape digits> [sample offset]\n"
860 " Send the given file, allowing playback to be interrupted by the given\n"
861 " digits, if any. Use double quotes for the digits if you wish none to be\n"
862 " permitted. If sample offset is provided then the audio will seek to sample\n"
863 " offset before play starts. Returns 0 if playback completes without a digit\n"
864 " being pressed, or the ASCII numerical value of the digit if one was pressed,\n"
865 " or -1 on error or if the channel was disconnected. Remember, the file\n"
866 " extension must not be included in the filename.\n";
868 static char usage_saynumber[] =
869 " Usage: SAY NUMBER <number> <escape digits>\n"
870 " Say a given number, returning early if any of the given DTMF digits\n"
871 " are received on the channel. Returns 0 if playback completes without a digit\n"
872 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
873 " -1 on error/hangup.\n";
875 static char usage_saydigits[] =
876 " Usage: SAY DIGITS <number> <escape digits>\n"
877 " Say a given digit string, returning early if any of the given DTMF digits\n"
878 " are received on the channel. Returns 0 if playback completes without a digit\n"
879 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
880 " -1 on error/hangup.\n";
882 static char usage_getdata[] =
883 " Usage: GET DATA <file to be streamed> [timeout] [max digits]\n"
884 " Stream the given file, and recieve DTMF data. Returns the digits recieved\n"
885 "from the channel at the other end.\n";
887 static char usage_setcontext[] =
888 " Usage: SET CONTEXT <desired context>\n"
889 " Sets the context for continuation upon exiting the application.\n";
891 static char usage_setextension[] =
892 " Usage: SET EXTENSION <new extension>\n"
893 " Changes the extension for continuation upon exiting the application.\n";
895 static char usage_setpriority[] =
896 " Usage: SET PRIORITY <num>\n"
897 " Changes the priority for continuation upon exiting the application.\n";
899 static char usage_recordfile[] =
900 " Usage: RECORD FILE <filename> <format> <escape digits> <timeout> [offset samples] [BEEP]\n"
901 " Record to a file until a given dtmf digit in the sequence is received\n"
902 " Returns -1 on hangup or error. The format will specify what kind of file\n"
903 " will be recorded. The timeout is the maximum record time in milliseconds, or\n"
904 " -1 for no timeout. Offset samples is optional, and if provided will seek to\n"
905 " the offset without exceeding the end of the file\n";
907 static char usage_autohangup[] =
908 " Usage: SET AUTOHANGUP <time>\n"
909 " Cause the channel to automatically hangup at <time> seconds in the\n"
910 "future. Of course it can be hungup before then as well. Setting to\n"
911 "0 will cause the autohangup feature to be disabled on this channel.\n";
913 static char usage_noop[] =
917 static agi_command commands[] = {
918 { { "answer", NULL }, handle_answer, "Asserts answer", usage_answer },
919 { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
920 { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
921 { { "receive", "char", NULL }, handle_recvchar, "Receives text from channels supporting it", usage_recvchar },
922 { { "tdd", "mode", NULL }, handle_tddmode, "Sends text to channels supporting it", usage_tddmode },
923 { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
924 { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
925 { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
926 { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
927 { { "get", "data", NULL }, handle_getdata, "Gets data on a channel", usage_getdata },
928 { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
929 { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
930 { { "set", "priority", NULL }, handle_setpriority, "Prioritizes the channel", usage_setpriority },
931 { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
932 { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
933 { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
934 { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
935 { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
936 { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus },
937 { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable },
938 { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable },
939 { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose },
940 { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget },
941 { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput },
942 { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel },
943 { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree },
944 { { "noop", NULL }, handle_noop, "Does nothing", usage_noop }
947 static void join(char *s, int len, char *w[])
950 /* Join words into a string */
954 strncat(s, " ", len - strlen(s));
955 strncat(s, w[x], len - strlen(s));
959 static int help_workhorse(int fd, char *match[])
964 struct agi_command *e;
966 join(matchstr, sizeof(matchstr), match);
967 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
970 join(fullcmd, sizeof(fullcmd), e->cmda);
971 /* Hide commands that start with '_' */
972 if (fullcmd[0] == '_')
975 if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
979 ast_cli(fd, "%20.20s %s\n", fullcmd, e->summary);
984 static agi_command *find_command(char *cmds[], int exact)
989 for (x=0;x < sizeof(commands) / sizeof(commands[0]);x++) {
990 /* start optimistic */
992 for (y=0;match && cmds[y]; y++) {
993 /* If there are no more words in the command (and we're looking for
994 an exact match) or there is a difference between the two words,
995 then this is not a match */
996 if (!commands[x].cmda[y] && !exact)
998 /* don't segfault if the next part of a command doesn't exist */
999 if (!commands[x].cmda[y]) return NULL;
1000 if (strcasecmp(commands[x].cmda[y], cmds[y]))
1003 /* If more words are needed to complete the command then this is not
1004 a candidate (unless we're looking for a really inexact answer */
1005 if ((exact > -1) && commands[x].cmda[y])
1008 return &commands[x];
1014 static int parse_args(char *s, int *max, char *argv[])
1026 /* If it's escaped, put a literal quote */
1031 if (quoted && whitespace) {
1032 /* If we're starting a quote, coming off white space start a new word, too */
1040 if (!quoted && !escaped) {
1041 /* If we're not quoted, mark this as whitespace, and
1042 end the previous argument */
1046 /* Otherwise, just treat it as anything else */
1050 /* If we're escaped, print a literal, otherwise enable escaping */
1060 if (x >= MAX_ARGS -1) {
1061 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1064 /* Coming off of whitespace, start the next argument */
1073 /* Null terminate */
1080 static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf)
1082 char *argv[MAX_ARGS];
1087 parse_args(buf, &argc, argv);
1090 for (x=0;x<argc;x++)
1091 fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
1093 c = find_command(argv, 0);
1095 res = c->handler(chan, agi, argc, argv);
1097 case RESULT_SHOWUSAGE:
1098 fdprintf(agi->fd, "520-Invalid command syntax. Proper usage follows:\n");
1099 fdprintf(agi->fd, c->usage);
1100 fdprintf(agi->fd, "520 End of proper usage.\n");
1102 case RESULT_FAILURE:
1103 /* They've already given the failure. We've been hung up on so handle this
1108 fdprintf(agi->fd, "510 Invalid or unknown command\n");
1113 static int run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid)
1115 struct ast_channel *c;
1118 int returnstatus = 0;
1119 struct ast_frame *f;
1122 if (!(readf = fdopen(agi->ctrl, "r"))) {
1123 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
1128 setup_env(chan, request, agi->fd, (agi->audio > -1));
1131 c = ast_waitfor_nandfds(&chan, 1, &agi->ctrl, 1, NULL, &outfd, &ms);
1133 /* Idle the channel until we get a command */
1136 ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
1140 /* If it's voice, write it to the audio pipe */
1141 if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
1142 /* Write, ignoring errors */
1143 write(agi->audio, f->data, f->datalen);
1147 } else if (outfd > -1) {
1148 if (!fgets(buf, sizeof(buf), readf)) {
1149 /* Program terminated */
1152 if (option_verbose > 2)
1153 ast_verbose(VERBOSE_PREFIX_3 "AGI Script %s completed, returning %d\n", request, returnstatus);
1154 /* No need to kill the pid anymore, since they closed us */
1158 /* get rid of trailing newline, if any */
1159 if (*buf && buf[strlen(buf) - 1] == '\n')
1160 buf[strlen(buf) - 1] = 0;
1162 returnstatus |= agi_handle_command(chan, agi, buf);
1163 /* If the handle_command returns -1, we need to stop */
1164 if (returnstatus < 0) {
1168 ast_log(LOG_WARNING, "No channel, no fd?\n");
1173 /* Notify process */
1177 return returnstatus;
1180 static int handle_showagi(int fd, int argc, char *argv[]) {
1181 struct agi_command *e;
1184 return RESULT_SHOWUSAGE;
1186 e = find_command(argv + 2, 1);
1188 ast_cli(fd, e->usage);
1190 if (find_command(argv + 2, -1)) {
1191 return help_workhorse(fd, argv + 1);
1193 join(fullcmd, sizeof(fullcmd), argv+1);
1194 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1198 return help_workhorse(fd, NULL);
1200 return RESULT_SUCCESS;
1203 static int handle_dumpagihtml(int fd, int argc, char *argv[]) {
1204 struct agi_command *e;
1211 return RESULT_SHOWUSAGE;
1213 if (!(htmlfile = fopen(argv[2], "wt"))) {
1214 ast_cli(fd, "Could not create file '%s'\n", argv[2]);
1215 return RESULT_SHOWUSAGE;
1218 fprintf(htmlfile, "<HTML>\n<HEAD>\n<TITLE>AGI Commands</TITLE>\n</HEAD>\n");
1219 fprintf(htmlfile, "<BODY>\n<CENTER><B><H1>AGI Commands</H1></B></CENTER>\n\n");
1222 fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
1224 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1228 join(fullcmd, sizeof(fullcmd), e->cmda);
1229 /* Hide commands that start with '_' */
1230 if (fullcmd[0] == '_')
1233 fprintf(htmlfile, "<TR><TD><TABLE BORDER=\"1\" CELLPADDING=\"5\" WIDTH=\"100%%\">\n");
1234 fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TD></TR>\n", fullcmd,e->summary);
1238 tempstr = strsep(&stringp, "\n");
1240 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">%s</TD></TR>\n", tempstr);
1242 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
1243 while ((tempstr = strsep(&stringp, "\n")) != NULL) {
1244 fprintf(htmlfile, "%s<BR>\n",tempstr);
1247 fprintf(htmlfile, "</TD></TR>\n");
1248 fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
1252 fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
1254 ast_cli(fd, "AGI HTML Commands Dumped to: %s\n", argv[2]);
1255 return RESULT_SUCCESS;
1258 static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced)
1261 struct localuser *u;
1269 if (!data || !strlen(data)) {
1270 ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
1275 memset(&agi, 0, sizeof(agi));
1276 strncpy(tmp, data, sizeof(tmp)-1);
1277 strsep(&stringp, "|");
1278 args = strsep(&stringp, "|");
1279 ringy = strsep(&stringp,"|");
1284 /* Answer if need be */
1285 if (chan->_state != AST_STATE_UP) {
1286 if (ringy) { /* if for ringing first */
1287 /* a little ringy-dingy first */
1288 ast_indicate(chan, AST_CONTROL_RINGING);
1291 if (ast_answer(chan)) {
1292 LOCAL_USER_REMOVE(u);
1297 res = launch_script(tmp, args, fds, enhanced ? &efd : NULL, &pid);
1302 res = run_agi(chan, tmp, &agi, pid);
1308 LOCAL_USER_REMOVE(u);
1312 static int agi_exec(struct ast_channel *chan, void *data)
1314 return agi_exec_full(chan, data, 0);
1317 static int eagi_exec(struct ast_channel *chan, void *data)
1321 readformat = chan->readformat;
1322 if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
1323 ast_log(LOG_WARNING, "Unable to set channel '%s' to linear mode\n", chan->name);
1326 res = agi_exec_full(chan, data, 1);
1328 if (ast_set_read_format(chan, readformat)) {
1329 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %d\n", chan->name, readformat);
1335 static char showagi_help[] =
1336 "Usage: show agi [topic]\n"
1337 " When called with a topic as an argument, displays usage\n"
1338 " information on the given command. If called without a\n"
1339 " topic, it provides a list of AGI commands.\n";
1342 static char dumpagihtml_help[] =
1343 "Usage: dump agihtml <filename>\n"
1344 " Dumps the agi command list in html format to given filename\n";
1346 static struct ast_cli_entry showagi =
1347 { { "show", "agi", NULL }, handle_showagi, "Show AGI commands or specific help", showagi_help };
1349 static struct ast_cli_entry dumpagihtml =
1350 { { "dump", "agihtml", NULL }, handle_dumpagihtml, "Dumps a list of agi command in html format", dumpagihtml_help };
1352 int unload_module(void)
1354 STANDARD_HANGUP_LOCALUSERS;
1355 ast_cli_unregister(&showagi);
1356 ast_cli_unregister(&dumpagihtml);
1357 ast_unregister_application(eapp);
1358 return ast_unregister_application(app);
1361 int load_module(void)
1363 ast_cli_register(&showagi);
1364 ast_cli_register(&dumpagihtml);
1365 ast_register_application(eapp, eagi_exec, synopsis, descrip);
1366 return ast_register_application(app, agi_exec, synopsis, descrip);
1369 char *description(void)
1377 STANDARD_USECOUNT(res);
1383 return ASTERISK_GPL_KEY;