2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief AGI - the Asterisk Gateway Interface
23 * \author Mark Spencer <markster@digium.com>
26 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <netinet/tcp.h>
31 #include <arpa/inet.h>
45 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
47 #include "asterisk/file.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/pbx.h"
51 #include "asterisk/module.h"
52 #include "asterisk/astdb.h"
53 #include "asterisk/callerid.h"
54 #include "asterisk/cli.h"
55 #include "asterisk/logger.h"
56 #include "asterisk/options.h"
57 #include "asterisk/image.h"
58 #include "asterisk/say.h"
59 #include "asterisk/app.h"
60 #include "asterisk/dsp.h"
61 #include "asterisk/musiconhold.h"
62 #include "asterisk/utils.h"
63 #include "asterisk/lock.h"
64 #include "asterisk/strings.h"
65 #include "asterisk/agi.h"
68 #define MAX_COMMANDS 128
70 /* Recycle some stuff from the CLI interface */
71 #define fdprintf agi_debug_cli
73 static char *app = "AGI";
75 static char *eapp = "EAGI";
77 static char *deadapp = "DeadAGI";
79 static char *synopsis = "Executes an AGI compliant application";
80 static char *esynopsis = "Executes an EAGI compliant application";
81 static char *deadsynopsis = "Executes AGI on a hungup channel";
83 static char *descrip =
84 " [E|Dead]AGI(command|args): Executes an Asterisk Gateway Interface compliant\n"
85 "program on a channel. AGI allows Asterisk to launch external programs\n"
86 "written in any language to control a telephony channel, play audio,\n"
87 "read DTMF digits, etc. by communicating with the AGI protocol on stdin\n"
89 " This channel will stop dialplan execution on hangup inside of this\n"
90 "application, except when using DeadAGI. Otherwise, dialplan execution\n"
91 "will continue normally.\n"
92 " Using 'EAGI' provides enhanced AGI, with incoming audio available out of band\n"
93 "on file descriptor 3\n\n"
94 " Use the CLI command 'show agi' to list available agi commands\n"
95 " This application sets the following channel variable upon completion:\n"
96 " AGISTATUS The status of the attempt to the run the AGI script\n"
97 " text string, one of SUCCESS | FAILED | HANGUP\n";
99 static int agidebug = 0;
101 struct module_symbols *me;
103 #define TONE_BLOCK_SIZE 200
105 /* Max time to connect to an AGI remote host */
106 #define MAX_AGI_CONNECT 2000
108 #define AGI_PORT 4573
116 static void agi_debug_cli(int fd, char *fmt, ...)
123 res = vasprintf(&stuff, fmt, ap);
126 ast_log(LOG_ERROR, "Out of memory\n");
129 ast_verbose("AGI Tx >> %s", stuff);
130 ast_carefulwrite(fd, stuff, strlen(stuff), 100);
135 /* launch_netscript: The fastagi handler.
136 FastAGI defaults to port 4573 */
137 static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds, int *efd, int *opid)
141 struct pollfd pfds[1];
143 char *c; int port = AGI_PORT;
145 struct sockaddr_in sin;
147 struct ast_hostent ahp;
149 /* agiusl is "agi://host.domain[:port][/script/name]" */
150 host = ast_strdupa(agiurl + 6); /* Remove agi:// */
151 /* Strip off any script name */
152 if ((c = strchr(host, '/'))) {
157 if ((c = strchr(host, ':'))) {
163 ast_log(LOG_WARNING, "AGI URI's don't support Enhanced AGI yet\n");
166 hp = ast_gethostbyname(host, &ahp);
168 ast_log(LOG_WARNING, "Unable to locate host '%s'\n", host);
171 s = socket(AF_INET, SOCK_STREAM, 0);
173 ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
176 flags = fcntl(s, F_GETFL);
178 ast_log(LOG_WARNING, "Fcntl(F_GETFL) failed: %s\n", strerror(errno));
182 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0) {
183 ast_log(LOG_WARNING, "Fnctl(F_SETFL) failed: %s\n", strerror(errno));
187 memset(&sin, 0, sizeof(sin));
188 sin.sin_family = AF_INET;
189 sin.sin_port = htons(port);
190 memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
191 if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) && (errno != EINPROGRESS)) {
192 ast_log(LOG_WARNING, "Connect failed with unexpected error: %s\n", strerror(errno));
194 return AGI_RESULT_FAILURE;
198 pfds[0].events = POLLOUT;
199 while (poll(pfds, 1, MAX_AGI_CONNECT) != 1) {
200 if (errno != EINTR) {
201 ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
203 return AGI_RESULT_FAILURE;
206 /* XXX in theory should check for partial writes... */
207 while (write(s, "agi_network: yes\n", strlen("agi_network: yes\n")) < 0) {
208 if (errno != EINTR) {
209 ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
211 return AGI_RESULT_FAILURE;
215 /* If we have a script parameter, relay it to the fastagi server */
216 if (!ast_strlen_zero(script))
217 fdprintf(s, "agi_network_script: %s\n", script);
219 if (option_debug > 3)
220 ast_log(LOG_DEBUG, "Wow, connected!\n");
224 return AGI_RESULT_SUCCESS;
227 static enum agi_result launch_script(char *script, char *argv[], int *fds, int *efd, int *opid)
238 if (!strncasecmp(script, "agi://", 6))
239 return launch_netscript(script, argv, fds, efd, opid);
241 if (script[0] != '/') {
242 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_AGI_DIR, script);
246 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
247 return AGI_RESULT_FAILURE;
250 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
253 return AGI_RESULT_FAILURE;
257 ast_log(LOG_WARNING, "unable to create audio pipe: %s\n", strerror(errno));
262 return AGI_RESULT_FAILURE;
264 res = fcntl(audio[1], F_GETFL);
266 res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
268 ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
275 return AGI_RESULT_FAILURE;
280 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
281 return AGI_RESULT_FAILURE;
284 /* Pass paths to AGI via environmental variables */
285 setenv("AST_CONFIG_DIR", ast_config_AST_CONFIG_DIR, 1);
286 setenv("AST_CONFIG_FILE", ast_config_AST_CONFIG_FILE, 1);
287 setenv("AST_MODULE_DIR", ast_config_AST_MODULE_DIR, 1);
288 setenv("AST_SPOOL_DIR", ast_config_AST_SPOOL_DIR, 1);
289 setenv("AST_MONITOR_DIR", ast_config_AST_MONITOR_DIR, 1);
290 setenv("AST_VAR_DIR", ast_config_AST_VAR_DIR, 1);
291 setenv("AST_DATA_DIR", ast_config_AST_DATA_DIR, 1);
292 setenv("AST_LOG_DIR", ast_config_AST_LOG_DIR, 1);
293 setenv("AST_AGI_DIR", ast_config_AST_AGI_DIR, 1);
294 setenv("AST_KEY_DIR", ast_config_AST_KEY_DIR, 1);
295 setenv("AST_RUN_DIR", ast_config_AST_RUN_DIR, 1);
297 /* Redirect stdin and out, provide enhanced audio channel if desired */
298 dup2(fromast[0], STDIN_FILENO);
299 dup2(toast[1], STDOUT_FILENO);
301 dup2(audio[0], STDERR_FILENO + 1);
303 close(STDERR_FILENO + 1);
306 /* unblock important signal handlers */
307 if (sigfillset(&signal_set) || pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
308 ast_log(LOG_WARNING, "unable to unblock signals for AGI script: %s\n", strerror(errno));
312 /* Close everything but stdin/out/error */
313 for (x=STDERR_FILENO + 2;x<1024;x++)
316 /* Don't run AGI scripts with realtime priority -- it causes audio stutter */
321 /* Can't use ast_log since FD's are closed */
322 fprintf(stdout, "verbose \"Failed to execute '%s': %s\" 2\n", script, strerror(errno));
326 if (option_verbose > 2)
327 ast_verbose(VERBOSE_PREFIX_3 "Launched AGI Script %s\n", script);
333 /* close what we're not using in the parent */
341 return AGI_RESULT_SUCCESS;
345 static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced)
347 /* Print initial environment, with agi_request always being the first
349 fdprintf(fd, "agi_request: %s\n", request);
350 fdprintf(fd, "agi_channel: %s\n", chan->name);
351 fdprintf(fd, "agi_language: %s\n", chan->language);
352 fdprintf(fd, "agi_type: %s\n", chan->tech->type);
353 fdprintf(fd, "agi_uniqueid: %s\n", chan->uniqueid);
356 fdprintf(fd, "agi_callerid: %s\n", S_OR(chan->cid.cid_num, "unknown"));
357 fdprintf(fd, "agi_calleridname: %s\n", S_OR(chan->cid.cid_name, "unknown"));
358 fdprintf(fd, "agi_callingpres: %d\n", chan->cid.cid_pres);
359 fdprintf(fd, "agi_callingani2: %d\n", chan->cid.cid_ani2);
360 fdprintf(fd, "agi_callington: %d\n", chan->cid.cid_ton);
361 fdprintf(fd, "agi_callingtns: %d\n", chan->cid.cid_tns);
362 fdprintf(fd, "agi_dnid: %s\n", S_OR(chan->cid.cid_dnid, "unknown"));
363 fdprintf(fd, "agi_rdnis: %s\n", S_OR(chan->cid.cid_rdnis, "unknown"));
365 /* Context information */
366 fdprintf(fd, "agi_context: %s\n", chan->context);
367 fdprintf(fd, "agi_extension: %s\n", chan->exten);
368 fdprintf(fd, "agi_priority: %d\n", chan->priority);
369 fdprintf(fd, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
371 /* User information */
372 fdprintf(fd, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
374 /* End with empty return */
378 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
382 if (chan->_state != AST_STATE_UP) {
383 /* Answer the chan */
384 res = ast_answer(chan);
386 fdprintf(agi->fd, "200 result=%d\n", res);
387 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
390 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
395 return RESULT_SHOWUSAGE;
396 if (sscanf(argv[3], "%d", &to) != 1)
397 return RESULT_SHOWUSAGE;
398 res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
399 fdprintf(agi->fd, "200 result=%d\n", res);
400 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
403 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
407 return RESULT_SHOWUSAGE;
408 /* At the moment, the parser (perhaps broken) returns with
409 the last argument PLUS the newline at the end of the input
410 buffer. This probably needs to be fixed, but I wont do that
411 because other stuff may break as a result. The right way
412 would probably be to strip off the trailing newline before
413 parsing, then here, add a newline at the end of the string
414 before sending it to ast_sendtext --DUDE */
415 res = ast_sendtext(chan, argv[2]);
416 fdprintf(agi->fd, "200 result=%d\n", res);
417 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
420 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
424 return RESULT_SHOWUSAGE;
425 res = ast_recvchar(chan,atoi(argv[2]));
427 fdprintf(agi->fd, "200 result=%d (timeout)\n", res);
428 return RESULT_SUCCESS;
431 fdprintf(agi->fd, "200 result=%d\n", res);
432 return RESULT_SUCCESS;
435 fdprintf(agi->fd, "200 result=%d (hangup)\n", res);
436 return RESULT_FAILURE;
440 static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
445 return RESULT_SHOWUSAGE;
446 buf = ast_recvtext(chan,atoi(argv[2]));
448 fdprintf(agi->fd, "200 result=1 (%s)\n", buf);
451 fdprintf(agi->fd, "200 result=-1\n");
453 return RESULT_SUCCESS;
456 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
460 return RESULT_SHOWUSAGE;
461 if (!strncasecmp(argv[2],"on",2))
465 if (!strncasecmp(argv[2],"mate",4))
467 if (!strncasecmp(argv[2],"tdd",3))
469 res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
470 if (res != RESULT_SUCCESS)
471 fdprintf(agi->fd, "200 result=0\n");
473 fdprintf(agi->fd, "200 result=1\n");
474 return RESULT_SUCCESS;
477 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
481 return RESULT_SHOWUSAGE;
482 res = ast_send_image(chan, argv[2]);
483 if (!ast_check_hangup(chan))
485 fdprintf(agi->fd, "200 result=%d\n", res);
486 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
489 static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
498 if (argc < 5 || argc > 9)
499 return RESULT_SHOWUSAGE;
501 if (!ast_strlen_zero(argv[4]))
506 if ((argc > 5) && (sscanf(argv[5], "%d", &skipms) != 1))
507 return RESULT_SHOWUSAGE;
509 if (argc > 6 && !ast_strlen_zero(argv[8]))
514 if (argc > 7 && !ast_strlen_zero(argv[8]))
519 if (argc > 8 && !ast_strlen_zero(argv[8]))
524 res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, pause, NULL, skipms);
526 fdprintf(agi->fd, "200 result=%d\n", res);
528 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
531 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
534 struct ast_filestream *fs;
535 long sample_offset = 0;
538 if (argc < 4 || argc > 5)
539 return RESULT_SHOWUSAGE;
540 if ((argc > 4) && (sscanf(argv[4], "%ld", &sample_offset) != 1))
541 return RESULT_SHOWUSAGE;
543 fs = ast_openstream(chan, argv[2], chan->language);
545 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
546 return RESULT_SUCCESS;
548 ast_seekstream(fs, 0, SEEK_END);
549 max_length = ast_tellstream(fs);
550 ast_seekstream(fs, sample_offset, SEEK_SET);
551 res = ast_applystream(chan, fs);
552 res = ast_playstream(fs);
554 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
555 return (res >= 0) ? RESULT_SHOWUSAGE : RESULT_FAILURE;
557 res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
558 /* this is to check for if ast_waitstream closed the stream, we probably are at
559 * the end of the stream, return that amount, else check for the amount */
560 sample_offset = (chan->stream) ? ast_tellstream(fs) : max_length;
561 ast_stopstream(chan);
563 /* Stop this command, don't print a result line, as there is a new command */
564 return RESULT_SUCCESS;
566 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
567 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
570 /* get option - really similar to the handle_streamfile, but with a timeout */
571 static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
574 struct ast_filestream *fs;
575 long sample_offset = 0;
578 char *edigits = NULL;
580 if ( argc < 4 || argc > 5 )
581 return RESULT_SHOWUSAGE;
587 timeout = atoi(argv[4]);
588 else if (chan->pbx->dtimeout) {
589 /* by default dtimeout is set to 5sec */
590 timeout = chan->pbx->dtimeout * 1000; /* in msec */
593 fs = ast_openstream(chan, argv[2], chan->language);
595 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
596 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
597 return RESULT_SUCCESS;
599 if (option_verbose > 2)
600 ast_verbose(VERBOSE_PREFIX_3 "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
602 ast_seekstream(fs, 0, SEEK_END);
603 max_length = ast_tellstream(fs);
604 ast_seekstream(fs, sample_offset, SEEK_SET);
605 res = ast_applystream(chan, fs);
606 res = ast_playstream(fs);
608 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
610 return RESULT_SHOWUSAGE;
612 return RESULT_FAILURE;
614 res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
615 /* this is to check for if ast_waitstream closed the stream, we probably are at
616 * the end of the stream, return that amount, else check for the amount */
617 sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
618 ast_stopstream(chan);
620 /* Stop this command, don't print a result line, as there is a new command */
621 return RESULT_SUCCESS;
624 /* If the user didnt press a key, wait for digitTimeout*/
626 res = ast_waitfordigit_full(chan, timeout, agi->audio, agi->ctrl);
627 /* Make sure the new result is in the escape digits of the GET OPTION */
628 if ( !strchr(edigits,res) )
632 fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
633 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
639 /*--- handle_saynumber: Say number in various language syntaxes ---*/
640 /* Need to add option for gender here as well. Coders wanted */
641 /* While waiting, we're sending a (char *) NULL. */
642 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
647 return RESULT_SHOWUSAGE;
648 if (sscanf(argv[2], "%d", &num) != 1)
649 return RESULT_SHOWUSAGE;
650 res = ast_say_number_full(chan, num, argv[3], chan->language, (char *) NULL, agi->audio, agi->ctrl);
652 return RESULT_SUCCESS;
653 fdprintf(agi->fd, "200 result=%d\n", res);
654 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
657 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
663 return RESULT_SHOWUSAGE;
664 if (sscanf(argv[2], "%d", &num) != 1)
665 return RESULT_SHOWUSAGE;
667 res = ast_say_digit_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
668 if (res == 1) /* New command */
669 return RESULT_SUCCESS;
670 fdprintf(agi->fd, "200 result=%d\n", res);
671 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
674 static int handle_sayalpha(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
679 return RESULT_SHOWUSAGE;
681 res = ast_say_character_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
682 if (res == 1) /* New command */
683 return RESULT_SUCCESS;
684 fdprintf(agi->fd, "200 result=%d\n", res);
685 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
688 static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
693 return RESULT_SHOWUSAGE;
694 if (sscanf(argv[2], "%d", &num) != 1)
695 return RESULT_SHOWUSAGE;
696 res = ast_say_date(chan, num, argv[3], chan->language);
698 return RESULT_SUCCESS;
699 fdprintf(agi->fd, "200 result=%d\n", res);
700 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
703 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
708 return RESULT_SHOWUSAGE;
709 if (sscanf(argv[2], "%d", &num) != 1)
710 return RESULT_SHOWUSAGE;
711 res = ast_say_time(chan, num, argv[3], chan->language);
713 return RESULT_SUCCESS;
714 fdprintf(agi->fd, "200 result=%d\n", res);
715 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
718 static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
722 char *format, *zone=NULL;
725 return RESULT_SHOWUSAGE;
730 /* XXX this doesn't belong here, but in the 'say' module */
731 if (!strcasecmp(chan->language, "de")) {
732 format = "A dBY HMS";
734 format = "ABdY 'digits/at' IMp";
738 if (argc > 5 && !ast_strlen_zero(argv[5]))
741 if (ast_get_time_t(argv[2], &unixtime, 0, NULL))
742 return RESULT_SHOWUSAGE;
744 res = ast_say_date_with_format(chan, unixtime, argv[3], chan->language, format, zone);
746 return RESULT_SUCCESS;
748 fdprintf(agi->fd, "200 result=%d\n", res);
749 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
752 static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
757 return RESULT_SHOWUSAGE;
759 res = ast_say_phonetic_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
760 if (res == 1) /* New command */
761 return RESULT_SUCCESS;
762 fdprintf(agi->fd, "200 result=%d\n", res);
763 return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
766 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
774 return RESULT_SHOWUSAGE;
776 timeout = atoi(argv[3]);
783 res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
784 if (res == 2) /* New command */
785 return RESULT_SUCCESS;
787 fdprintf(agi->fd, "200 result=%s (timeout)\n", data);
789 fdprintf(agi->fd, "200 result=-1\n");
791 fdprintf(agi->fd, "200 result=%s\n", data);
792 return RESULT_SUCCESS;
795 static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
799 return RESULT_SHOWUSAGE;
800 ast_copy_string(chan->context, argv[2], sizeof(chan->context));
801 fdprintf(agi->fd, "200 result=0\n");
802 return RESULT_SUCCESS;
805 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, char **argv)
808 return RESULT_SHOWUSAGE;
809 ast_copy_string(chan->exten, argv[2], sizeof(chan->exten));
810 fdprintf(agi->fd, "200 result=0\n");
811 return RESULT_SUCCESS;
814 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char **argv)
818 return RESULT_SHOWUSAGE;
820 if (sscanf(argv[2], "%d", &pri) != 1) {
821 if ((pri = ast_findlabel_extension(chan, chan->context, chan->exten, argv[2], chan->cid.cid_num)) < 1)
822 return RESULT_SHOWUSAGE;
825 ast_explicit_goto(chan, NULL, NULL, pri);
826 fdprintf(agi->fd, "200 result=0\n");
827 return RESULT_SUCCESS;
830 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
832 struct ast_filestream *fs;
834 struct timeval start;
835 long sample_offset = 0;
839 struct ast_dsp *sildet=NULL; /* silence detector dsp */
840 int totalsilence = 0;
842 int silence = 0; /* amount of silence to allow */
843 int gotsilence = 0; /* did we timeout for silence? */
844 char *silencestr=NULL;
848 /* XXX EAGI FIXME XXX */
851 return RESULT_SHOWUSAGE;
852 if (sscanf(argv[5], "%d", &ms) != 1)
853 return RESULT_SHOWUSAGE;
856 silencestr = strchr(argv[6],'s');
857 if ((argc > 7) && (!silencestr))
858 silencestr = strchr(argv[7],'s');
859 if ((argc > 8) && (!silencestr))
860 silencestr = strchr(argv[8],'s');
863 if (strlen(silencestr) > 2) {
864 if ((silencestr[0] == 's') && (silencestr[1] == '=')) {
868 silence = atoi(silencestr);
876 rfmt = chan->readformat;
877 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
879 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
882 sildet = ast_dsp_new();
884 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
887 ast_dsp_set_threshold(sildet, 256);
890 /* backward compatibility, if no offset given, arg[6] would have been
891 * caught below and taken to be a beep, else if it is a digit then it is a
893 if ((argc >6) && (sscanf(argv[6], "%ld", &sample_offset) != 1) && (!strchr(argv[6], '=')))
894 res = ast_streamfile(chan, "beep", chan->language);
896 if ((argc > 7) && (!strchr(argv[7], '=')))
897 res = ast_streamfile(chan, "beep", chan->language);
900 res = ast_waitstream(chan, argv[4]);
902 fdprintf(agi->fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
904 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, 0644);
907 fdprintf(agi->fd, "200 result=%d (writefile)\n", res);
909 ast_dsp_free(sildet);
910 return RESULT_FAILURE;
913 /* Request a video update */
914 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
917 ast_applystream(chan,fs);
918 /* really should have checks */
919 ast_seekstream(fs, sample_offset, SEEK_SET);
923 while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
924 res = ast_waitfor(chan, -1);
927 fdprintf(agi->fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
929 ast_dsp_free(sildet);
930 return RESULT_FAILURE;
934 fdprintf(agi->fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
937 ast_dsp_free(sildet);
938 return RESULT_FAILURE;
940 switch(f->frametype) {
942 if (strchr(argv[4], f->subclass)) {
943 /* This is an interrupting chracter, so rewind to chop off any small
944 amount of DTMF that may have been recorded
946 ast_stream_rewind(fs, 200);
948 sample_offset = ast_tellstream(fs);
949 fdprintf(agi->fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
953 ast_dsp_free(sildet);
954 return RESULT_SUCCESS;
957 case AST_FRAME_VOICE:
958 ast_writestream(fs, f);
959 /* this is a safe place to check progress since we know that fs
960 * is valid after a write, and it will then have our current
962 sample_offset = ast_tellstream(fs);
965 ast_dsp_silence(sildet, f, &dspsilence);
967 totalsilence = dspsilence;
971 if (totalsilence > silence) {
972 /* Ended happily with silence */
979 case AST_FRAME_VIDEO:
980 ast_writestream(fs, f);
989 ast_stream_rewind(fs, silence-1000);
991 sample_offset = ast_tellstream(fs);
993 fdprintf(agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
998 res = ast_set_read_format(chan, rfmt);
1000 ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
1001 ast_dsp_free(sildet);
1003 return RESULT_SUCCESS;
1006 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
1011 return RESULT_SHOWUSAGE;
1012 if (sscanf(argv[2], "%d", &timeout) != 1)
1013 return RESULT_SHOWUSAGE;
1017 chan->whentohangup = time(NULL) + timeout;
1019 chan->whentohangup = 0;
1020 fdprintf(agi->fd, "200 result=0\n");
1021 return RESULT_SUCCESS;
1024 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1026 struct ast_channel *c;
1028 /* no argument: hangup the current channel */
1029 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
1030 fdprintf(agi->fd, "200 result=1\n");
1031 return RESULT_SUCCESS;
1032 } else if (argc == 2) {
1033 /* one argument: look for info on the specified channel */
1034 c = ast_get_channel_by_name_locked(argv[1]);
1036 /* we have a matching channel */
1037 ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
1038 fdprintf(agi->fd, "200 result=1\n");
1039 ast_channel_unlock(c);
1040 return RESULT_SUCCESS;
1042 /* if we get this far no channel name matched the argument given */
1043 fdprintf(agi->fd, "200 result=-1\n");
1044 return RESULT_SUCCESS;
1046 return RESULT_SHOWUSAGE;
1050 static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1053 struct ast_app *app;
1056 return RESULT_SHOWUSAGE;
1058 if (option_verbose > 2)
1059 ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
1061 app = pbx_findapp(argv[1]);
1064 res = pbx_exec(chan, app, argv[2]);
1066 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
1069 fdprintf(agi->fd, "200 result=%d\n", res);
1074 static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1077 char *l = NULL, *n = NULL;
1080 ast_copy_string(tmp, argv[2], sizeof(tmp));
1081 ast_callerid_parse(tmp, &n, &l);
1083 ast_shrink_phone_number(l);
1088 ast_set_callerid(chan, l, n, NULL);
1091 fdprintf(agi->fd, "200 result=1\n");
1092 return RESULT_SUCCESS;
1095 static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1097 struct ast_channel *c;
1099 /* no argument: supply info on the current channel */
1100 fdprintf(agi->fd, "200 result=%d\n", chan->_state);
1101 return RESULT_SUCCESS;
1102 } else if (argc == 3) {
1103 /* one argument: look for info on the specified channel */
1104 c = ast_get_channel_by_name_locked(argv[2]);
1106 fdprintf(agi->fd, "200 result=%d\n", c->_state);
1107 ast_channel_unlock(c);
1108 return RESULT_SUCCESS;
1110 /* if we get this far no channel name matched the argument given */
1111 fdprintf(agi->fd, "200 result=-1\n");
1112 return RESULT_SUCCESS;
1114 return RESULT_SHOWUSAGE;
1118 static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1121 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
1123 fdprintf(agi->fd, "200 result=1\n");
1124 return RESULT_SUCCESS;
1127 static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1133 return RESULT_SHOWUSAGE;
1135 /* check if we want to execute an ast_custom_function */
1136 if (!ast_strlen_zero(argv[2]) && (argv[2][strlen(argv[2]) - 1] == ')')) {
1137 ret = ast_func_read(chan, argv[2], tempstr, sizeof(tempstr)) ? NULL : tempstr;
1139 pbx_retrieve_variable(chan, argv[2], &ret, tempstr, sizeof(tempstr), NULL);
1143 fdprintf(agi->fd, "200 result=1 (%s)\n", ret);
1145 fdprintf(agi->fd, "200 result=0\n");
1147 return RESULT_SUCCESS;
1150 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1152 char tmp[4096] = "";
1153 struct ast_channel *chan2=NULL;
1155 if ((argc != 4) && (argc != 5))
1156 return RESULT_SHOWUSAGE;
1158 chan2 = ast_get_channel_by_name_locked(argv[4]);
1162 if (chan) { /* XXX isn't this chan2 ? */
1163 pbx_substitute_variables_helper(chan2, argv[3], tmp, sizeof(tmp) - 1);
1164 fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
1166 fdprintf(agi->fd, "200 result=0\n");
1168 if (chan2 && (chan2 != chan))
1169 ast_channel_unlock(chan2);
1170 return RESULT_SUCCESS;
1173 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1179 return RESULT_SHOWUSAGE;
1182 sscanf(argv[2], "%d", &level);
1186 prefix = VERBOSE_PREFIX_4;
1189 prefix = VERBOSE_PREFIX_3;
1192 prefix = VERBOSE_PREFIX_2;
1196 prefix = VERBOSE_PREFIX_1;
1200 if (level <= option_verbose)
1201 ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
1203 fdprintf(agi->fd, "200 result=1\n");
1205 return RESULT_SUCCESS;
1208 static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1214 return RESULT_SHOWUSAGE;
1215 res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
1217 fdprintf(agi->fd, "200 result=0\n");
1219 fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
1221 return RESULT_SUCCESS;
1224 static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1229 return RESULT_SHOWUSAGE;
1230 res = ast_db_put(argv[2], argv[3], argv[4]);
1231 fdprintf(agi->fd, "200 result=%c\n", res ? '0' : '1');
1232 return RESULT_SUCCESS;
1235 static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1240 return RESULT_SHOWUSAGE;
1241 res = ast_db_del(argv[2], argv[3]);
1242 fdprintf(agi->fd, "200 result=%c\n", res ? '0' : '1');
1243 return RESULT_SUCCESS;
1246 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char **argv)
1249 if ((argc < 3) || (argc > 4))
1250 return RESULT_SHOWUSAGE;
1252 res = ast_db_deltree(argv[2], argv[3]);
1254 res = ast_db_deltree(argv[2], NULL);
1256 fdprintf(agi->fd, "200 result=%c\n", res ? '0' : '1');
1257 return RESULT_SUCCESS;
1260 static char debug_usage[] =
1261 "Usage: agi debug\n"
1262 " Enables dumping of AGI transactions for debugging purposes\n";
1264 static char no_debug_usage[] =
1265 "Usage: agi no debug\n"
1266 " Disables dumping of AGI transactions for debugging purposes\n";
1268 static int agi_do_debug(int fd, int argc, char *argv[])
1271 return RESULT_SHOWUSAGE;
1273 ast_cli(fd, "AGI Debugging Enabled\n");
1274 return RESULT_SUCCESS;
1277 static int agi_no_debug(int fd, int argc, char *argv[])
1280 return RESULT_SHOWUSAGE;
1282 ast_cli(fd, "AGI Debugging Disabled\n");
1283 return RESULT_SUCCESS;
1286 static struct ast_cli_entry cli_debug =
1287 { { "agi", "debug", NULL }, agi_do_debug, "Enable AGI debugging", debug_usage };
1289 static struct ast_cli_entry cli_no_debug =
1290 { { "agi", "no", "debug", NULL }, agi_no_debug, "Disable AGI debugging", no_debug_usage };
1292 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
1294 fdprintf(agi->fd, "200 result=0\n");
1295 return RESULT_SUCCESS;
1298 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
1300 if (!strncasecmp(argv[2], "on", 2))
1301 ast_moh_start(chan, argc > 3 ? argv[3] : NULL);
1302 else if (!strncasecmp(argv[2], "off", 3))
1304 fdprintf(agi->fd, "200 result=0\n");
1305 return RESULT_SUCCESS;
1308 static char usage_setmusic[] =
1309 " Usage: SET MUSIC ON <on|off> <class>\n"
1310 " Enables/Disables the music on hold generator. If <class> is\n"
1311 " not specified, then the default music on hold class will be used.\n"
1312 " Always returns 0.\n";
1314 static char usage_dbput[] =
1315 " Usage: DATABASE PUT <family> <key> <value>\n"
1316 " Adds or updates an entry in the Asterisk database for a\n"
1317 " given family, key, and value.\n"
1318 " Returns 1 if successful, 0 otherwise.\n";
1320 static char usage_dbget[] =
1321 " Usage: DATABASE GET <family> <key>\n"
1322 " Retrieves an entry in the Asterisk database for a\n"
1323 " given family and key.\n"
1324 " Returns 0 if <key> is not set. Returns 1 if <key>\n"
1325 " is set and returns the variable in parentheses.\n"
1326 " Example return code: 200 result=1 (testvariable)\n";
1328 static char usage_dbdel[] =
1329 " Usage: DATABASE DEL <family> <key>\n"
1330 " Deletes an entry in the Asterisk database for a\n"
1331 " given family and key.\n"
1332 " Returns 1 if successful, 0 otherwise.\n";
1334 static char usage_dbdeltree[] =
1335 " Usage: DATABASE DELTREE <family> [keytree]\n"
1336 " Deletes a family or specific keytree within a family\n"
1337 " in the Asterisk database.\n"
1338 " Returns 1 if successful, 0 otherwise.\n";
1340 static char usage_verbose[] =
1341 " Usage: VERBOSE <message> <level>\n"
1342 " Sends <message> to the console via verbose message system.\n"
1343 " <level> is the the verbose level (1-4)\n"
1344 " Always returns 1.\n";
1346 static char usage_getvariable[] =
1347 " Usage: GET VARIABLE <variablename>\n"
1348 " Returns 0 if <variablename> is not set. Returns 1 if <variablename>\n"
1349 " is set and returns the variable in parentheses.\n"
1350 " example return code: 200 result=1 (testvariable)\n";
1352 static char usage_getvariablefull[] =
1353 " Usage: GET FULL VARIABLE <variablename> [<channel name>]\n"
1354 " Returns 0 if <variablename> is not set or channel does not exist. Returns 1\n"
1355 "if <variablename> is set and returns the variable in parenthesis. Understands\n"
1356 "complex variable names and builtin variables, unlike GET VARIABLE.\n"
1357 " example return code: 200 result=1 (testvariable)\n";
1359 static char usage_setvariable[] =
1360 " Usage: SET VARIABLE <variablename> <value>\n";
1362 static char usage_channelstatus[] =
1363 " Usage: CHANNEL STATUS [<channelname>]\n"
1364 " Returns the status of the specified channel.\n"
1365 " If no channel name is given the returns the status of the\n"
1366 " current channel. Return values:\n"
1367 " 0 Channel is down and available\n"
1368 " 1 Channel is down, but reserved\n"
1369 " 2 Channel is off hook\n"
1370 " 3 Digits (or equivalent) have been dialed\n"
1371 " 4 Line is ringing\n"
1372 " 5 Remote end is ringing\n"
1374 " 7 Line is busy\n";
1376 static char usage_setcallerid[] =
1377 " Usage: SET CALLERID <number>\n"
1378 " Changes the callerid of the current channel.\n";
1380 static char usage_exec[] =
1381 " Usage: EXEC <application> <options>\n"
1382 " Executes <application> with given <options>.\n"
1383 " Returns whatever the application returns, or -2 on failure to find application\n";
1385 static char usage_hangup[] =
1386 " Usage: HANGUP [<channelname>]\n"
1387 " Hangs up the specified channel.\n"
1388 " If no channel name is given, hangs up the current channel\n";
1390 static char usage_answer[] =
1392 " Answers channel if not already in answer state. Returns -1 on\n"
1393 " channel failure, or 0 if successful.\n";
1395 static char usage_waitfordigit[] =
1396 " Usage: WAIT FOR DIGIT <timeout>\n"
1397 " Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
1398 " Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
1399 " the numerical value of the ascii of the digit if one is received. Use -1\n"
1400 " for the timeout value if you desire the call to block indefinitely.\n";
1402 static char usage_sendtext[] =
1403 " Usage: SEND TEXT \"<text to send>\"\n"
1404 " Sends the given text on a channel. Most channels do not support the\n"
1405 " transmission of text. Returns 0 if text is sent, or if the channel does not\n"
1406 " support text transmission. Returns -1 only on error/hangup. Text\n"
1407 " consisting of greater than one word should be placed in quotes since the\n"
1408 " command only accepts a single argument.\n";
1410 static char usage_recvchar[] =
1411 " Usage: RECEIVE CHAR <timeout>\n"
1412 " Receives a character of text on a channel. Specify timeout to be the\n"
1413 " maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
1414 " do not support the reception of text. Returns the decimal value of the character\n"
1415 " if one is received, or 0 if the channel does not support text reception. Returns\n"
1416 " -1 only on error/hangup.\n";
1418 static char usage_recvtext[] =
1419 " Usage: RECEIVE TEXT <timeout>\n"
1420 " Receives a string of text on a channel. Specify timeout to be the\n"
1421 " maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
1422 " do not support the reception of text. Returns -1 for failure or 1 for success, and the string in parentheses.\n";
1424 static char usage_tddmode[] =
1425 " Usage: TDD MODE <on|off>\n"
1426 " Enable/Disable TDD transmission/reception on a channel. Returns 1 if\n"
1427 " successful, or 0 if channel is not TDD-capable.\n";
1429 static char usage_sendimage[] =
1430 " Usage: SEND IMAGE <image>\n"
1431 " Sends the given image on a channel. Most channels do not support the\n"
1432 " transmission of images. Returns 0 if image is sent, or if the channel does not\n"
1433 " support image transmission. Returns -1 only on error/hangup. Image names\n"
1434 " should not include extensions.\n";
1436 static char usage_streamfile[] =
1437 " Usage: STREAM FILE <filename> <escape digits> [sample offset]\n"
1438 " Send the given file, allowing playback to be interrupted by the given\n"
1439 " digits, if any. Use double quotes for the digits if you wish none to be\n"
1440 " permitted. If sample offset is provided then the audio will seek to sample\n"
1441 " offset before play starts. Returns 0 if playback completes without a digit\n"
1442 " being pressed, or the ASCII numerical value of the digit if one was pressed,\n"
1443 " or -1 on error or if the channel was disconnected. Remember, the file\n"
1444 " extension must not be included in the filename.\n";
1446 static char usage_controlstreamfile[] =
1447 " Usage: CONTROL STREAM FILE <filename> <escape digits> [skipms] [ffchar] [rewchr] [pausechr]\n"
1448 " Send the given file, allowing playback to be controled by the given\n"
1449 " digits, if any. Use double quotes for the digits if you wish none to be\n"
1450 " permitted. Returns 0 if playback completes without a digit\n"
1451 " being pressed, or the ASCII numerical value of the digit if one was pressed,\n"
1452 " or -1 on error or if the channel was disconnected. Remember, the file\n"
1453 " extension must not be included in the filename.\n\n"
1454 " Note: ffchar and rewchar default to * and # respectively.\n";
1456 static char usage_getoption[] =
1457 " Usage: GET OPTION <filename> <escape_digits> [timeout]\n"
1458 " Behaves similar to STREAM FILE but used with a timeout option.\n";
1460 static char usage_saynumber[] =
1461 " Usage: SAY NUMBER <number> <escape digits>\n"
1462 " Say a given number, returning early if any of the given DTMF digits\n"
1463 " are received on the channel. Returns 0 if playback completes without a digit\n"
1464 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
1465 " -1 on error/hangup.\n";
1467 static char usage_saydigits[] =
1468 " Usage: SAY DIGITS <number> <escape digits>\n"
1469 " Say a given digit string, returning early if any of the given DTMF digits\n"
1470 " are received on the channel. Returns 0 if playback completes without a digit\n"
1471 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
1472 " -1 on error/hangup.\n";
1474 static char usage_sayalpha[] =
1475 " Usage: SAY ALPHA <number> <escape digits>\n"
1476 " Say a given character string, returning early if any of the given DTMF digits\n"
1477 " are received on the channel. Returns 0 if playback completes without a digit\n"
1478 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
1479 " -1 on error/hangup.\n";
1481 static char usage_saydate[] =
1482 " Usage: SAY DATE <date> <escape digits>\n"
1483 " Say a given date, returning early if any of the given DTMF digits are\n"
1484 " received on the channel. <date> is number of seconds elapsed since 00:00:00\n"
1485 " on January 1, 1970, Coordinated Universal Time (UTC). Returns 0 if playback\n"
1486 " completes without a digit being pressed, or the ASCII numerical value of the\n"
1487 " digit if one was pressed or -1 on error/hangup.\n";
1489 static char usage_saytime[] =
1490 " Usage: SAY TIME <time> <escape digits>\n"
1491 " Say a given time, returning early if any of the given DTMF digits are\n"
1492 " received on the channel. <time> is number of seconds elapsed since 00:00:00\n"
1493 " on January 1, 1970, Coordinated Universal Time (UTC). Returns 0 if playback\n"
1494 " completes without a digit being pressed, or the ASCII numerical value of the\n"
1495 " digit if one was pressed or -1 on error/hangup.\n";
1497 static char usage_saydatetime[] =
1498 " Usage: SAY DATETIME <time> <escape digits> [format] [timezone]\n"
1499 " Say a given time, returning early if any of the given DTMF digits are\n"
1500 " received on the channel. <time> is number of seconds elapsed since 00:00:00\n"
1501 " on January 1, 1970, Coordinated Universal Time (UTC). [format] is the format\n"
1502 " the time should be said in. See voicemail.conf (defaults to \"ABdY\n"
1503 " 'digits/at' IMp\"). Acceptable values for [timezone] can be found in\n"
1504 " /usr/share/zoneinfo. Defaults to machine default. Returns 0 if playback\n"
1505 " completes without a digit being pressed, or the ASCII numerical value of the\n"
1506 " digit if one was pressed or -1 on error/hangup.\n";
1508 static char usage_sayphonetic[] =
1509 " Usage: SAY PHONETIC <string> <escape digits>\n"
1510 " Say a given character string with phonetics, returning early if any of the\n"
1511 " given DTMF digits are received on the channel. Returns 0 if playback\n"
1512 " completes without a digit pressed, the ASCII numerical value of the digit\n"
1513 " if one was pressed, or -1 on error/hangup.\n";
1515 static char usage_getdata[] =
1516 " Usage: GET DATA <file to be streamed> [timeout] [max digits]\n"
1517 " Stream the given file, and recieve DTMF data. Returns the digits received\n"
1518 "from the channel at the other end.\n";
1520 static char usage_setcontext[] =
1521 " Usage: SET CONTEXT <desired context>\n"
1522 " Sets the context for continuation upon exiting the application.\n";
1524 static char usage_setextension[] =
1525 " Usage: SET EXTENSION <new extension>\n"
1526 " Changes the extension for continuation upon exiting the application.\n";
1528 static char usage_setpriority[] =
1529 " Usage: SET PRIORITY <priority>\n"
1530 " Changes the priority for continuation upon exiting the application.\n"
1531 " The priority must be a valid priority or label.\n";
1533 static char usage_recordfile[] =
1534 " Usage: RECORD FILE <filename> <format> <escape digits> <timeout> \\\n"
1535 " [offset samples] [BEEP] [s=silence]\n"
1536 " Record to a file until a given dtmf digit in the sequence is received\n"
1537 " Returns -1 on hangup or error. The format will specify what kind of file\n"
1538 " will be recorded. The timeout is the maximum record time in milliseconds, or\n"
1539 " -1 for no timeout. \"Offset samples\" is optional, and, if provided, will seek\n"
1540 " to the offset without exceeding the end of the file. \"silence\" is the number\n"
1541 " of seconds of silence allowed before the function returns despite the\n"
1542 " lack of dtmf digits or reaching timeout. Silence value must be\n"
1543 " preceeded by \"s=\" and is also optional.\n";
1545 static char usage_autohangup[] =
1546 " Usage: SET AUTOHANGUP <time>\n"
1547 " Cause the channel to automatically hangup at <time> seconds in the\n"
1548 " future. Of course it can be hungup before then as well. Setting to 0 will\n"
1549 " cause the autohangup feature to be disabled on this channel.\n";
1551 static char usage_noop[] =
1555 static agi_command commands[MAX_COMMANDS] = {
1556 { { "answer", NULL }, handle_answer, "Answer channel", usage_answer },
1557 { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus },
1558 { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel },
1559 { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree },
1560 { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget },
1561 { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput },
1562 { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
1563 { { "get", "data", NULL }, handle_getdata, "Prompts for DTMF on a channel", usage_getdata },
1564 { { "get", "full", "variable", NULL }, handle_getvariablefull, "Evaluates a channel expression", usage_getvariablefull },
1565 { { "get", "option", NULL }, handle_getoption, "Stream file, prompt for DTMF, with timeout", usage_getoption },
1566 { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable },
1567 { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
1568 { { "noop", NULL }, handle_noop, "Does nothing", usage_noop },
1569 { { "receive", "char", NULL }, handle_recvchar, "Receives one character from channels supporting it", usage_recvchar },
1570 { { "receive", "text", NULL }, handle_recvtext, "Receives text from channels supporting it", usage_recvtext },
1571 { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
1572 { { "say", "alpha", NULL }, handle_sayalpha, "Says a given character string", usage_sayalpha },
1573 { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
1574 { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
1575 { { "say", "phonetic", NULL }, handle_sayphonetic, "Says a given character string with phonetics", usage_sayphonetic },
1576 { { "say", "date", NULL }, handle_saydate, "Says a given date", usage_saydate },
1577 { { "say", "time", NULL }, handle_saytime, "Says a given time", usage_saytime },
1578 { { "say", "datetime", NULL }, handle_saydatetime, "Says a given time as specfied by the format given", usage_saydatetime },
1579 { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
1580 { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
1581 { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
1582 { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
1583 { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
1584 { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
1585 { { "set", "music", NULL }, handle_setmusic, "Enable/Disable Music on hold generator", usage_setmusic },
1586 { { "set", "priority", NULL }, handle_setpriority, "Set channel dialplan priority", usage_setpriority },
1587 { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable },
1588 { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
1589 { { "control", "stream", "file", NULL }, handle_controlstreamfile, "Sends audio file on channel and allows the listner to control the stream", usage_controlstreamfile },
1590 { { "tdd", "mode", NULL }, handle_tddmode, "Toggles TDD mode (for the deaf)", usage_tddmode },
1591 { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose },
1592 { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
1595 static int help_workhorse(int fd, char *match[])
1600 struct agi_command *e;
1602 ast_join(matchstr, sizeof(matchstr), match);
1603 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1607 /* Hide commands that start with '_' */
1608 if ((e->cmda[0])[0] == '_')
1610 ast_join(fullcmd, sizeof(fullcmd), e->cmda);
1611 if (match && strncasecmp(matchstr, fullcmd, strlen(matchstr)))
1613 ast_cli(fd, "%20.20s %s\n", fullcmd, e->summary);
1618 int agi_register(agi_command *agi)
1621 for (x=0; x<MAX_COMMANDS - 1; x++) {
1622 if (commands[x].cmda[0] == agi->cmda[0]) {
1623 ast_log(LOG_WARNING, "Command already registered!\n");
1627 for (x=0; x<MAX_COMMANDS - 1; x++) {
1628 if (!commands[x].cmda[0]) {
1633 ast_log(LOG_WARNING, "No more room for new commands!\n");
1637 void agi_unregister(agi_command *agi)
1640 for (x=0; x<MAX_COMMANDS - 1; x++) {
1641 if (commands[x].cmda[0] == agi->cmda[0]) {
1642 memset(&commands[x], 0, sizeof(agi_command));
1647 static agi_command *find_command(char *cmds[], int exact)
1653 for (x=0; x < sizeof(commands) / sizeof(commands[0]); x++) {
1654 if (!commands[x].cmda[0])
1656 /* start optimistic */
1658 for (y=0; match && cmds[y]; y++) {
1659 /* If there are no more words in the command (and we're looking for
1660 an exact match) or there is a difference between the two words,
1661 then this is not a match */
1662 if (!commands[x].cmda[y] && !exact)
1664 /* don't segfault if the next part of a command doesn't exist */
1665 if (!commands[x].cmda[y])
1667 if (strcasecmp(commands[x].cmda[y], cmds[y]))
1670 /* If more words are needed to complete the command then this is not
1671 a candidate (unless we're looking for a really inexact answer */
1672 if ((exact > -1) && commands[x].cmda[y])
1675 return &commands[x];
1681 static int parse_args(char *s, int *max, char *argv[])
1693 /* If it's escaped, put a literal quote */
1698 if (quoted && whitespace) {
1699 /* If we're starting a quote, coming off white space start a new word, too */
1707 if (!quoted && !escaped) {
1708 /* If we're not quoted, mark this as whitespace, and
1709 end the previous argument */
1713 /* Otherwise, just treat it as anything else */
1717 /* If we're escaped, print a literal, otherwise enable escaping */
1727 if (x >= MAX_ARGS -1) {
1728 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1731 /* Coming off of whitespace, start the next argument */
1740 /* Null terminate */
1747 static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf)
1749 char *argv[MAX_ARGS];
1750 int argc = MAX_ARGS;
1754 parse_args(buf, &argc, argv);
1757 for (x=0; x<argc; x++)
1758 fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
1760 c = find_command(argv, 0);
1762 res = c->handler(chan, agi, argc, argv);
1764 case RESULT_SHOWUSAGE:
1765 fdprintf(agi->fd, "520-Invalid command syntax. Proper usage follows:\n");
1766 fdprintf(agi->fd, c->usage);
1767 fdprintf(agi->fd, "520 End of proper usage.\n");
1769 case AST_PBX_KEEPALIVE:
1770 /* We've been asked to keep alive, so do so */
1771 return AST_PBX_KEEPALIVE;
1773 case RESULT_FAILURE:
1774 /* They've already given the failure. We've been hung up on so handle this
1779 fdprintf(agi->fd, "510 Invalid or unknown command\n");
1784 static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid, int dead)
1786 struct ast_channel *c;
1789 enum agi_result returnstatus = AGI_RESULT_SUCCESS;
1790 struct ast_frame *f;
1793 /* how many times we'll retry if ast_waitfor_nandfs will return without either
1794 channel or file descriptor in case select is interrupted by a system call (EINTR) */
1797 if (!(readf = fdopen(agi->ctrl, "r"))) {
1798 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
1802 return AGI_RESULT_FAILURE;
1805 setup_env(chan, request, agi->fd, (agi->audio > -1));
1808 c = ast_waitfor_nandfds(&chan, dead ? 0 : 1, &agi->ctrl, 1, NULL, &outfd, &ms);
1811 /* Idle the channel until we get a command */
1814 ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
1815 returnstatus = AGI_RESULT_HANGUP;
1818 /* If it's voice, write it to the audio pipe */
1819 if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
1820 /* Write, ignoring errors */
1821 write(agi->audio, f->data, f->datalen);
1825 } else if (outfd > -1) {
1827 if (!fgets(buf, sizeof(buf), readf)) {
1828 /* Program terminated */
1831 if (option_verbose > 2)
1832 ast_verbose(VERBOSE_PREFIX_3 "AGI Script %s completed, returning %d\n", request, returnstatus);
1833 /* No need to kill the pid anymore, since they closed us */
1837 /* get rid of trailing newline, if any */
1838 if (*buf && buf[strlen(buf) - 1] == '\n')
1839 buf[strlen(buf) - 1] = 0;
1841 ast_verbose("AGI Rx << %s\n", buf);
1842 returnstatus |= agi_handle_command(chan, agi, buf);
1843 /* If the handle_command returns -1, we need to stop */
1844 if ((returnstatus < 0) || (returnstatus == AST_PBX_KEEPALIVE)) {
1849 ast_log(LOG_WARNING, "No channel, no fd?\n");
1850 returnstatus = AGI_RESULT_FAILURE;
1855 /* Notify process */
1857 if (kill(pid, SIGHUP))
1858 ast_log(LOG_WARNING, "unable to send SIGHUP to AGI process %d: %s\n", pid, strerror(errno));
1861 return returnstatus;
1864 static int handle_showagi(int fd, int argc, char *argv[])
1866 struct agi_command *e;
1869 return RESULT_SHOWUSAGE;
1871 e = find_command(argv + 2, 1);
1873 ast_cli(fd, e->usage);
1875 if (find_command(argv + 2, -1)) {
1876 return help_workhorse(fd, argv + 1);
1878 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1879 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1883 return help_workhorse(fd, NULL);
1885 return RESULT_SUCCESS;
1888 static int handle_dumpagihtml(int fd, int argc, char *argv[])
1890 struct agi_command *e;
1896 return RESULT_SHOWUSAGE;
1898 if (!(htmlfile = fopen(argv[2], "wt"))) {
1899 ast_cli(fd, "Could not create file '%s'\n", argv[2]);
1900 return RESULT_SHOWUSAGE;
1903 fprintf(htmlfile, "<HTML>\n<HEAD>\n<TITLE>AGI Commands</TITLE>\n</HEAD>\n");
1904 fprintf(htmlfile, "<BODY>\n<CENTER><B><H1>AGI Commands</H1></B></CENTER>\n\n");
1907 fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
1909 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1910 char *stringp, *tempstr;
1913 if (!e->cmda[0]) /* end ? */
1915 /* Hide commands that start with '_' */
1916 if ((e->cmda[0])[0] == '_')
1918 ast_join(fullcmd, sizeof(fullcmd), e->cmda);
1920 fprintf(htmlfile, "<TR><TD><TABLE BORDER=\"1\" CELLPADDING=\"5\" WIDTH=\"100%%\">\n");
1921 fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TD></TR>\n", fullcmd,e->summary);
1924 tempstr = strsep(&stringp, "\n");
1926 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">%s</TD></TR>\n", tempstr);
1928 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
1929 while ((tempstr = strsep(&stringp, "\n")) != NULL)
1930 fprintf(htmlfile, "%s<BR>\n",tempstr);
1931 fprintf(htmlfile, "</TD></TR>\n");
1932 fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
1936 fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
1938 ast_cli(fd, "AGI HTML Commands Dumped to: %s\n", argv[2]);
1939 return RESULT_SUCCESS;
1942 static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced, int dead)
1944 enum agi_result res;
1945 struct localuser *u;
1946 char *argv[MAX_ARGS];
1948 char *tmp = (char *)buf;
1956 if (ast_strlen_zero(data)) {
1957 ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
1960 ast_copy_string(buf, data, sizeof(buf));
1962 memset(&agi, 0, sizeof(agi));
1963 while ((stringp = strsep(&tmp, "|")) && argc < MAX_ARGS-1)
1964 argv[argc++] = stringp;
1967 u = ast_localuser_add(me, chan);
1969 /* Answer if need be */
1970 if (chan->_state != AST_STATE_UP) {
1971 if (ast_answer(chan)) {
1972 LOCAL_USER_REMOVE(u);
1977 res = launch_script(argv[0], argv, fds, enhanced ? &efd : NULL, &pid);
1978 if (res == AGI_RESULT_SUCCESS) {
1982 res = run_agi(chan, argv[0], &agi, pid, dead);
1987 ast_localuser_remove(me, u);
1990 case AGI_RESULT_SUCCESS:
1991 pbx_builtin_setvar_helper(chan, "AGISTATUS", "SUCCESS");
1993 case AGI_RESULT_FAILURE:
1994 pbx_builtin_setvar_helper(chan, "AGISTATUS", "FAILURE");
1996 case AGI_RESULT_HANGUP:
1997 pbx_builtin_setvar_helper(chan, "AGISTATUS", "HANGUP");
2004 static int agi_exec(struct ast_channel *chan, void *data)
2006 if (chan->_softhangup)
2007 ast_log(LOG_WARNING, "If you want to run AGI on hungup channels you should use DeadAGI!\n");
2008 return agi_exec_full(chan, data, 0, 0);
2011 static int eagi_exec(struct ast_channel *chan, void *data)
2016 if (chan->_softhangup)
2017 ast_log(LOG_WARNING, "If you want to run AGI on hungup channels you should use DeadAGI!\n");
2018 readformat = chan->readformat;
2019 if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
2020 ast_log(LOG_WARNING, "Unable to set channel '%s' to linear mode\n", chan->name);
2023 res = agi_exec_full(chan, data, 1, 0);
2025 if (ast_set_read_format(chan, readformat)) {
2026 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %s\n", chan->name, ast_getformatname(readformat));
2032 static int deadagi_exec(struct ast_channel *chan, void *data)
2034 return agi_exec_full(chan, data, 0, 1);
2037 static char showagi_help[] =
2038 "Usage: show agi [topic]\n"
2039 " When called with a topic as an argument, displays usage\n"
2040 " information on the given command. If called without a\n"
2041 " topic, it provides a list of AGI commands.\n";
2044 static char dumpagihtml_help[] =
2045 "Usage: dump agihtml <filename>\n"
2046 " Dumps the agi command list in html format to given filename\n";
2048 static struct ast_cli_entry showagi =
2049 { { "show", "agi", NULL }, handle_showagi, "Show AGI commands or specific help", showagi_help };
2051 static struct ast_cli_entry dumpagihtml =
2052 { { "dump", "agihtml", NULL }, handle_dumpagihtml, "Dumps a list of agi command in html format", dumpagihtml_help };
2054 static int unload_module(void *mod)
2056 ast_hangup_localusers(mod);
2057 ast_cli_unregister(&showagi);
2058 ast_cli_unregister(&dumpagihtml);
2059 ast_cli_unregister(&cli_debug);
2060 ast_cli_unregister(&cli_no_debug);
2061 ast_unregister_application(eapp);
2062 ast_unregister_application(deadapp);
2063 return ast_unregister_application(app);
2066 static int load_module(void *mod)
2069 ast_cli_register(&showagi);
2070 ast_cli_register(&dumpagihtml);
2071 ast_cli_register(&cli_debug);
2072 ast_cli_register(&cli_no_debug);
2073 ast_register_application(deadapp, deadagi_exec, deadsynopsis, descrip);
2074 ast_register_application(eapp, eagi_exec, esynopsis, descrip);
2075 return ast_register_application(app, agi_exec, synopsis, descrip);
2078 static const char *description(void)
2080 return "Asterisk Gateway Interface (AGI)";
2083 static const char *key(void)
2085 return ASTERISK_GPL_KEY;
2088 STD_MOD(MOD_0, NULL, NULL, NULL);