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 <asterisk/file.h>
15 #include <asterisk/logger.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/pbx.h>
18 #include <asterisk/module.h>
19 #include <asterisk/astdb.h>
25 #include <sys/signal.h>
30 #include <asterisk/cli.h>
31 #include <asterisk/logger.h>
32 #include <asterisk/options.h>
33 #include <asterisk/image.h>
34 #include <asterisk/say.h>
35 #include "../asterisk.h"
36 #include "../astconf.h"
42 /* Recycle some stuff from the CLI interface */
43 #define fdprintf ast_cli
45 typedef struct agi_command {
46 /* Null terminated list of the words of the command */
47 char *cmda[AST_MAX_CMD_LEN];
48 /* Handler for the command (fd for output, # of arguments, argument list).
49 Returns RESULT_SHOWUSAGE for improper arguments */
50 int (*handler)(struct ast_channel *chan, int fd, int argc, char *argv[]);
51 /* Summary of the command (< 60 characters) */
53 /* Detailed usage information */
57 static char *tdesc = "Asterisk Gateway Interface (AGI)";
59 static char *app = "AGI";
61 static char *synopsis = "Executes an AGI compliant application";
63 static char *descrip =
64 " AGI(command|args): Executes an Asterisk Gateway Interface compliant\n"
65 "program on a channel. AGI allows Asterisk to launch external programs\n"
66 "written in any language to control a telephony channel, play audio,\n"
67 "read DTMF digits, etc. by communicating with the AGI protocol on stdin\n"
68 "and stdout. Returns -1 on hangup or if application requested hangup, or\n"
69 "0 on non-hangup exit.\n";
75 extern char *pbx_builtin_getvar_helper(struct ast_channel *chan, char *name);
76 extern void pbx_builtin_setvar_helper(struct ast_channel *chan, char *name, char *value);
78 #define TONE_BLOCK_SIZE 200
80 static float loudness = 8192.0;
82 unsigned char linear2ulaw(short sample);
83 static void make_tone_block(unsigned char *data, float f1, int *x);
85 static void make_tone_block(unsigned char *data, float f1, int *x)
90 for(i = 0; i < TONE_BLOCK_SIZE; i++)
92 val = loudness * sin((f1 * 2.0 * M_PI * (*x)++)/8000.0);
93 data[i] = linear2ulaw((int)val);
95 /* wrap back around from 8000 */
96 if (*x >= 8000) *x = 0;
100 static int launch_script(char *script, char *args, int *fds, int *opid)
107 if (script[0] != '/') {
108 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_AGI_DIR, script);
112 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
116 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
123 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
127 /* Redirect stdin and out */
128 dup2(fromast[0], STDIN_FILENO);
129 dup2(toast[1], STDOUT_FILENO);
130 /* Close everything but stdin/out/error */
131 for (x=STDERR_FILENO + 1;x<1024;x++)
134 execl(script, script, args, NULL);
135 /* Can't use ast_log since FD's are closed */
136 fprintf(stderr, "Failed to execute '%s': %s\n", script, strerror(errno));
139 if (option_verbose > 2)
140 ast_verbose(VERBOSE_PREFIX_3 "Launched AGI Script %s\n", script);
143 /* close what we're not using in the parent */
151 static void setup_env(struct ast_channel *chan, char *request, int fd)
153 /* Print initial environment, with agi_request always being the first
155 fdprintf(fd, "agi_request: %s\n", request);
156 fdprintf(fd, "agi_channel: %s\n", chan->name);
157 fdprintf(fd, "agi_language: %s\n", chan->language);
158 fdprintf(fd, "agi_type: %s\n", chan->type);
161 fdprintf(fd, "agi_callerid: %s\n", chan->callerid ? chan->callerid : "");
162 fdprintf(fd, "agi_dnid: %s\n", chan->dnid ? chan->dnid : "");
163 fdprintf(fd, "agi_rdnis: %s\n", chan->rdnis ? chan->rdnis : "");
165 /* Context information */
166 fdprintf(fd, "agi_context: %s\n", chan->context);
167 fdprintf(fd, "agi_extension: %s\n", chan->exten);
168 fdprintf(fd, "agi_priority: %d\n", chan->priority);
170 /* End with empty return */
174 static int handle_answer(struct ast_channel *chan, int fd, int argc, char *argv[])
178 if (chan->_state != AST_STATE_UP) {
179 /* Answer the chan */
180 res = ast_answer(chan);
182 fdprintf(fd, "200 result=%d\n", res);
184 return RESULT_SUCCESS;
186 return RESULT_FAILURE;
189 static int handle_waitfordigit(struct ast_channel *chan, int fd, int argc, char *argv[])
194 return RESULT_SHOWUSAGE;
195 if (sscanf(argv[3], "%i", &to) != 1)
196 return RESULT_SHOWUSAGE;
197 res = ast_waitfordigit(chan, to);
198 fdprintf(fd, "200 result=%d\n", res);
200 return RESULT_SUCCESS;
202 return RESULT_FAILURE;
205 static int handle_sendtext(struct ast_channel *chan, int fd, int argc, char *argv[])
209 return RESULT_SHOWUSAGE;
210 /* At the moment, the parser (perhaps broken) returns with
211 the last argument PLUS the newline at the end of the input
212 buffer. This probably needs to be fixed, but I wont do that
213 because other stuff may break as a result. The right way
214 would probably be to strip off the trailing newline before
215 parsing, then here, add a newline at the end of the string
216 before sending it to ast_sendtext --DUDE */
217 res = ast_sendtext(chan, argv[2]);
218 fdprintf(fd, "200 result=%d\n", res);
220 return RESULT_SUCCESS;
222 return RESULT_FAILURE;
225 static int handle_recvchar(struct ast_channel *chan, int fd, int argc, char *argv[])
229 return RESULT_SHOWUSAGE;
230 res = ast_recvchar(chan,atoi(argv[2]));
232 fdprintf(fd, "200 result=%d (timeout)\n", res);
233 return RESULT_SUCCESS;
236 fdprintf(fd, "200 result=%d\n", res);
237 return RESULT_SUCCESS;
240 fdprintf(fd, "200 result=%d (hangup)\n", res);
241 return RESULT_FAILURE;
245 static int handle_tddmode(struct ast_channel *chan, int fd, int argc, char *argv[])
249 return RESULT_SHOWUSAGE;
250 if (!strncasecmp(argv[2],"on",2)) x = 1; else x = 0;
251 if (!strncasecmp(argv[2],"mate",4)) x = 2;
252 if (!strncasecmp(argv[2],"tdd",3)) x = 1;
253 res = ast_channel_setoption(chan,AST_OPTION_TDD,&x,sizeof(char),0);
254 fdprintf(fd, "200 result=%d\n", res);
256 return RESULT_SUCCESS;
258 return RESULT_FAILURE;
261 static int handle_sendimage(struct ast_channel *chan, int fd, int argc, char *argv[])
265 return RESULT_SHOWUSAGE;
266 res = ast_send_image(chan, argv[2]);
267 if (!ast_check_hangup(chan))
269 fdprintf(fd, "200 result=%d\n", res);
271 return RESULT_SUCCESS;
273 return RESULT_FAILURE;
276 static int handle_streamfile(struct ast_channel *chan, int fd, int argc, char *argv[])
279 struct ast_filestream *fs;
280 long sample_offset = 0;
284 return RESULT_SHOWUSAGE;
286 return RESULT_SHOWUSAGE;
287 if ((argc > 4) && (sscanf(argv[4], "%ld", &sample_offset) != 1))
288 return RESULT_SHOWUSAGE;
290 fs = ast_openstream(chan, argv[2], chan->language);
292 fdprintf(fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
293 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
294 return RESULT_FAILURE;
296 ast_seekstream(fs, 0, SEEK_END);
297 max_length = ast_tellstream(fs);
298 ast_seekstream(fs, sample_offset, SEEK_SET);
299 res = ast_applystream(chan, fs);
300 res = ast_playstream(fs);
302 fdprintf(fd, "200 result=%d endpos=%ld\n", res, sample_offset);
304 return RESULT_SHOWUSAGE;
306 return RESULT_FAILURE;
308 res = ast_waitstream(chan, argv[3]);
309 /* this is to check for if ast_waitstream closed the stream, we probably are at
310 * the end of the stream, return that amount, else check for the amount */
311 sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
312 ast_stopstream(chan);
313 fdprintf(fd, "200 result=%d endpos=%ld\n", res, sample_offset);
315 return RESULT_SUCCESS;
317 return RESULT_FAILURE;
320 static int handle_saynumber(struct ast_channel *chan, int fd, int argc, char *argv[])
325 return RESULT_SHOWUSAGE;
326 if (sscanf(argv[2], "%i", &num) != 1)
327 return RESULT_SHOWUSAGE;
328 res = ast_say_number(chan, num, argv[3], chan->language);
329 fdprintf(fd, "200 result=%d\n", res);
331 return RESULT_SUCCESS;
333 return RESULT_FAILURE;
336 static int handle_saydigits(struct ast_channel *chan, int fd, int argc, char *argv[])
341 return RESULT_SHOWUSAGE;
342 if (sscanf(argv[2], "%i", &num) != 1)
343 return RESULT_SHOWUSAGE;
344 res = ast_say_digit_str(chan, argv[2], argv[3], chan->language);
345 fdprintf(fd, "200 result=%d\n", res);
347 return RESULT_SUCCESS;
349 return RESULT_FAILURE;
352 int ast_app_getdata(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout);
354 static int handle_getdata(struct ast_channel *chan, int fd, int argc, char *argv[])
362 return RESULT_SHOWUSAGE;
363 if (argc >= 4) timeout = atoi(argv[3]); else timeout = 0;
364 if (argc >= 5) max = atoi(argv[4]); else max = 50;
365 res = ast_app_getdata(chan, argv[2], data, max, timeout);
367 fdprintf(fd, "200 result=%s (timeout)\n", data);
369 fdprintf(fd, "200 result=%s\n", data);
371 return RESULT_SUCCESS;
373 return RESULT_FAILURE;
376 static int handle_setcontext(struct ast_channel *chan, int fd, int argc, char *argv[])
380 return RESULT_SHOWUSAGE;
381 strncpy(chan->context, argv[2], sizeof(chan->context)-1);
382 fdprintf(fd, "200 result=0\n");
383 return RESULT_SUCCESS;
386 static int handle_setextension(struct ast_channel *chan, int fd, int argc, char **argv)
389 return RESULT_SHOWUSAGE;
390 strncpy(chan->exten, argv[2], sizeof(chan->exten)-1);
391 fdprintf(fd, "200 result=0\n");
392 return RESULT_SUCCESS;
395 static int handle_setpriority(struct ast_channel *chan, int fd, int argc, char **argv)
399 return RESULT_SHOWUSAGE;
400 if (sscanf(argv[2], "%i", &pri) != 1)
401 return RESULT_SHOWUSAGE;
402 chan->priority = pri - 1;
403 fdprintf(fd, "200 result=0\n");
404 return RESULT_SUCCESS;
407 static int ms_diff(struct timeval *tv1, struct timeval *tv2)
411 ms = (tv1->tv_sec - tv2->tv_sec) * 1000;
412 ms += (tv1->tv_usec - tv2->tv_usec) / 1000;
416 static int handle_recordfile(struct ast_channel *chan, int fd, int argc, char *argv[])
418 struct ast_filestream *fs;
420 struct timeval tv, start;
421 long sample_offset = 0;
426 return RESULT_SHOWUSAGE;
427 if (sscanf(argv[5], "%i", &ms) != 1)
428 return RESULT_SHOWUSAGE;
429 /* backward compatibility, if no offset given, arg[6] would have been
430 * caught below and taken to be a beep, else if it is a digit then it is a
432 if ((argc >6) && (sscanf(argv[6], "%ld", &sample_offset) != 1))
433 res = ast_streamfile(chan, "beep", chan->language);
436 res = ast_streamfile(chan, "beep", chan->language);
438 res = ast_waitstream(chan, argv[4]);
440 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY, 0, 0644);
443 fdprintf(fd, "200 result=%d (writefile)\n", res);
444 return RESULT_FAILURE;
448 ast_applystream(chan,fs);
449 /* really should have checks */
450 ast_seekstream(fs, sample_offset, SEEK_SET);
453 gettimeofday(&start, NULL);
454 gettimeofday(&tv, NULL);
455 while ((ms < 0) || (((tv.tv_sec - start.tv_sec) * 1000 + (tv.tv_usec - start.tv_usec)/1000) < ms)) {
456 res = ast_waitfor(chan, -1);
459 fdprintf(fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
460 return RESULT_FAILURE;
464 fdprintf(fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
466 return RESULT_FAILURE;
468 switch(f->frametype) {
470 if (strchr(argv[4], f->subclass)) {
471 /* This is an interrupting chracter */
472 sample_offset = ast_tellstream(fs);
473 fdprintf(fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
476 return RESULT_SUCCESS;
479 case AST_FRAME_VOICE:
480 ast_writestream(fs, f);
481 /* this is a safe place to check progress since we know that fs
482 * is valid after a write, and it will then have our current
484 sample_offset = ast_tellstream(fs);
488 gettimeofday(&tv, NULL);
490 fdprintf(fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
493 fdprintf(fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
494 return RESULT_SUCCESS;
497 static int handle_autohangup(struct ast_channel *chan, int fd, int argc, char *argv[])
502 return RESULT_SHOWUSAGE;
503 if (sscanf(argv[2], "%d", &timeout) != 1)
504 return RESULT_SHOWUSAGE;
508 chan->whentohangup = time(NULL) + timeout;
510 chan->whentohangup = 0;
511 fdprintf(fd, "200 result=0\n");
512 return RESULT_SUCCESS;
515 static int handle_hangup(struct ast_channel *chan, int fd, int argc, char **argv)
517 struct ast_channel *c;
519 /* no argument: hangup the current channel */
520 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
521 fdprintf(fd, "200 result=1\n");
522 return RESULT_SUCCESS;
523 } else if (argc==2) {
524 /* one argument: look for info on the specified channel */
525 c = ast_channel_walk(NULL);
527 if (strcasecmp(argv[1],c->name)==0) {
528 /* we have a matching channel */
529 ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
530 fdprintf(fd, "200 result=1\n");
531 return RESULT_SUCCESS;
533 c = ast_channel_walk(c);
535 /* if we get this far no channel name matched the argument given */
536 fdprintf(fd, "200 result=-1\n");
537 return RESULT_SUCCESS;
539 return RESULT_SHOWUSAGE;
543 static int handle_exec(struct ast_channel *chan, int fd, int argc, char **argv)
549 return RESULT_SHOWUSAGE;
551 if (option_verbose > 2)
552 ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
554 app = pbx_findapp(argv[1]);
557 res = pbx_exec(chan, app, argv[2], 1);
559 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
562 fdprintf(fd, "200 result=%d\n", res);
567 static int handle_setcallerid(struct ast_channel *chan, int fd, int argc, char **argv)
570 ast_set_callerid(chan, argv[2], 0);
572 /* strncpy(chan->callerid, argv[2], sizeof(chan->callerid)-1);
573 */ fdprintf(fd, "200 result=1\n");
574 return RESULT_SUCCESS;
577 static int handle_channelstatus(struct ast_channel *chan, int fd, int argc, char **argv)
579 struct ast_channel *c;
581 /* no argument: supply info on the current channel */
582 fdprintf(fd, "200 result=%d\n", chan->_state);
583 return RESULT_SUCCESS;
584 } else if (argc==3) {
585 /* one argument: look for info on the specified channel */
586 c = ast_channel_walk(NULL);
588 if (strcasecmp(argv[2],c->name)==0) {
589 fdprintf(fd, "200 result=%d\n", c->_state);
590 return RESULT_SUCCESS;
592 c = ast_channel_walk(c);
594 /* if we get this far no channel name matched the argument given */
595 fdprintf(fd, "200 result=-1\n");
596 return RESULT_SUCCESS;
598 return RESULT_SHOWUSAGE;
602 static int handle_setvariable(struct ast_channel *chan, int fd, int argc, char **argv)
605 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
607 fdprintf(fd, "200 result=1\n");
608 return RESULT_SUCCESS;
611 static int handle_getvariable(struct ast_channel *chan, int fd, int argc, char **argv)
615 if ((tempstr = pbx_builtin_getvar_helper(chan, argv[2])) )
616 fdprintf(fd, "200 result=1 (%s)\n", tempstr);
618 fdprintf(fd, "200 result=0\n");
620 return RESULT_SUCCESS;
623 static int handle_verbose(struct ast_channel *chan, int fd, int argc, char **argv)
629 return RESULT_SHOWUSAGE;
632 sscanf(argv[2], "%d", &level);
636 prefix = VERBOSE_PREFIX_4;
639 prefix = VERBOSE_PREFIX_3;
642 prefix = VERBOSE_PREFIX_2;
646 prefix = VERBOSE_PREFIX_1;
650 if (level <= option_verbose)
651 ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
653 fdprintf(fd, "200 result=1\n");
655 return RESULT_SUCCESS;
658 static int handle_dbget(struct ast_channel *chan, int fd, int argc, char **argv)
663 return RESULT_SHOWUSAGE;
664 res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
666 fdprintf(fd, "200 result=0\n");
668 fdprintf(fd, "200 result=1 (%s)\n", tmp);
670 return RESULT_SUCCESS;
673 static int handle_dbput(struct ast_channel *chan, int fd, int argc, char **argv)
677 return RESULT_SHOWUSAGE;
678 res = ast_db_put(argv[2], argv[3], argv[4]);
680 fdprintf(fd, "200 result=0\n");
682 fdprintf(fd, "200 result=1\n");
684 return RESULT_SUCCESS;
687 static int handle_dbdel(struct ast_channel *chan, int fd, int argc, char **argv)
691 return RESULT_SHOWUSAGE;
692 res = ast_db_del(argv[2], argv[3]);
694 fdprintf(fd, "200 result=0\n");
696 fdprintf(fd, "200 result=1\n");
698 return RESULT_SUCCESS;
701 static int handle_dbdeltree(struct ast_channel *chan, int fd, int argc, char **argv)
704 if ((argc < 3) || (argc > 4))
705 return RESULT_SHOWUSAGE;
707 res = ast_db_deltree(argv[2], argv[3]);
709 res = ast_db_deltree(argv[2], NULL);
712 fdprintf(fd, "200 result=0\n");
714 fdprintf(fd, "200 result=1\n");
715 return RESULT_SUCCESS;
718 static char usage_dbput[] =
719 " Usage: DATABASE PUT <family> <key> <value>\n"
720 " Adds or updates an entry in the Asterisk database for a\n"
721 " given family, key, and value.\n"
722 " Returns 1 if succesful, 0 otherwise\n";
724 static char usage_dbget[] =
725 " Usage: DATABASE GET <family> <key>\n"
726 " Retrieves an entry in the Asterisk database for a\n"
727 " given family and key.\n"
728 " Returns 0 if <key> is not set. Returns 1 if <key>\n"
729 " is set and returns the variable in parenthesis\n"
730 " example return code: 200 result=1 (testvariable)\n";
732 static char usage_dbdel[] =
733 " Usage: DATABASE DEL <family> <key>\n"
734 " Deletes an entry in the Asterisk database for a\n"
735 " given family and key.\n"
736 " Returns 1 if succesful, 0 otherwise\n";
738 static char usage_dbdeltree[] =
739 " Usage: DATABASE DELTREE <family> [keytree]\n"
740 " Deletes a family or specific keytree withing a family\n"
741 " in the Asterisk database.\n"
742 " Returns 1 if succesful, 0 otherwise\n";
744 static char usage_verbose[] =
745 " Usage: VERBOSE <message> <level>\n"
746 " Sends <message> to the console via verbose message system.\n"
747 " <level> is the the verbose level (1-4)\n"
748 " Always returns 1\n";
750 static char usage_getvariable[] =
751 " Usage: GET VARIABLE <variablename>\n"
752 " Returns 0 if <variablename> is not set. Returns 1 if <variablename>\n"
753 " is set and returns the variable in parenthesis\n"
754 " example return code: 200 result=1 (testvariable)\n";
756 static char usage_setvariable[] =
757 " Usage: SET VARIABLE <variablename> <value>\n";
759 static char usage_channelstatus[] =
760 " Usage: CHANNEL STATUS [<channelname>]\n"
761 " Returns the status of the specified channel.\n"
762 " If no channel name is given the returns the status of the\n"
763 " current channel.\n"
765 " 0 Channel is down and available\n"
766 " 1 Channel is down, but reserved\n"
767 " 2 Channel is off hook\n"
768 " 3 Digits (or equivalent) have been dialed\n"
769 " 4 Line is ringing\n"
770 " 5 Remote end is ringing\n"
774 static char usage_setcallerid[] =
775 " Usage: SET CALLERID <number>\n"
776 " Changes the callerid of the current channel.\n";
778 static char usage_exec[] =
779 " Usage: EXEC <application> <options>\n"
780 " Executes <application> with given <options>.\n"
781 " Returns whatever the application returns, or -2 on failure to find application\n";
783 static char usage_hangup[] =
784 " Usage: HANGUP [<channelname>]\n"
785 " Hangs up the specified channel.\n"
786 " If no channel name is given, hangs up the current channel\n";
788 static char usage_answer[] =
790 " Answers channel if not already in answer state. Returns -1 on\n"
791 " channel failure, or 0 if successful.\n";
793 static char usage_waitfordigit[] =
794 " Usage: WAIT FOR DIGIT <timeout>\n"
795 " Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
796 " Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
797 " the numerical value of the ascii of the digit if one is received. Use -1\n"
798 " for the timeout value if you desire the call to block indefinitely.\n";
800 static char usage_sendtext[] =
801 " Usage: SEND TEXT \"<text to send>\"\n"
802 " Sends the given text on a channel. Most channels do not support the\n"
803 " transmission of text. Returns 0 if text is sent, or if the channel does not\n"
804 " support text transmission. Returns -1 only on error/hangup. Text\n"
805 " consisting of greater than one word should be placed in quotes since the\n"
806 " command only accepts a single argument.\n";
808 static char usage_recvchar[] =
809 " Usage: RECEIVE CHAR <timeout>\n"
810 " Receives a character of text on a channel. Specify timeout to be the\n"
811 " maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
812 " do not support the reception of text. Returns the decimal value of the character\n"
813 " if one is received, or 0 if the channel does not support text reception. Returns\n"
814 " -1 only on error/hangup.\n";
816 static char usage_tddmode[] =
817 " Usage: TDD MODE <on|off>\n"
818 " Enable/Disable TDD transmission/reception on a channel. Returns 1 if\n"
819 " successful, or 0 if channel is not TDD-capable.\n";
821 static char usage_sendimage[] =
822 " Usage: SEND IMAGE <image>\n"
823 " Sends the given image on a channel. Most channels do not support the\n"
824 " transmission of images. Returns 0 if image is sent, or if the channel does not\n"
825 " support image transmission. Returns -1 only on error/hangup. Image names\n"
826 " should not include extensions.\n";
828 static char usage_streamfile[] =
829 " Usage: STREAM FILE <filename> <escape digits> [sample offset]\n"
830 " Send the given file, allowing playback to be interrupted by the given\n"
831 " digits, if any. Use double quotes for the digits if you wish none to be\n"
832 " permitted. If sample offset is provided then the audio will seek to sample\n"
833 " offset before play starts. Returns 0 if playback completes without a digit\n"
834 " being pressed, or the ASCII numerical value of the digit if one was pressed,\n"
835 " or -1 on error or if the channel was disconnected. Remember, the file\n"
836 " extension must not be included in the filename.\n";
838 static char usage_saynumber[] =
839 " Usage: SAY NUMBER <number> <escape digits>\n"
840 " Say a given number, returning early if any of the given DTMF digits\n"
841 " are received on the channel. Returns 0 if playback completes without a digit\n"
842 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
843 " -1 on error/hangup.\n";
845 static char usage_saydigits[] =
846 " Usage: SAY DIGITS <number> <escape digits>\n"
847 " Say a given digit string, returning early if any of the given DTMF digits\n"
848 " are received on the channel. Returns 0 if playback completes without a digit\n"
849 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
850 " -1 on error/hangup.\n";
852 static char usage_getdata[] =
853 " Usage: GET DATA <file to be streamed> [timeout] [max digits]\n"
854 " Stream the given file, and recieve DTMF data. Returns the digits recieved\n"
855 "from the channel at the other end.\n";
857 static char usage_setcontext[] =
858 " Usage: SET CONTEXT <desired context>\n"
859 " Sets the context for continuation upon exiting the application.\n";
861 static char usage_setextension[] =
862 " Usage: SET EXTENSION <new extension>\n"
863 " Changes the extension for continuation upon exiting the application.\n";
865 static char usage_setpriority[] =
866 " Usage: SET PRIORITY <num>\n"
867 " Changes the priority for continuation upon exiting the application.\n";
869 static char usage_recordfile[] =
870 " Usage: RECORD FILE <filename> <format> <escape digits> <timeout> [offset samples] [BEEP]\n"
871 " Record to a file until a given dtmf digit in the sequence is received\n"
872 " Returns -1 on hangup or error. The format will specify what kind of file\n"
873 " will be recorded. The timeout is the maximum record time in milliseconds, or\n"
874 " -1 for no timeout. Offset samples is optional, and if provided will seek to\n"
875 " the offset without exceeding the end of the file\n";
877 static char usage_autohangup[] =
878 " Usage: SET AUTOHANGUP <time>\n"
879 " Cause the channel to automatically hangup at <time> seconds in the\n"
880 "future. Of course it can be hungup before then as well. Setting to\n"
881 "0 will cause the autohangup feature to be disabled on this channel.\n";
883 agi_command commands[] = {
884 { { "answer", NULL }, handle_answer, "Asserts answer", usage_answer },
885 { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
886 { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
887 { { "receive", "char", NULL }, handle_recvchar, "Receives text from channels supporting it", usage_recvchar },
888 { { "tdd", "mode", NULL }, handle_tddmode, "Sends text to channels supporting it", usage_tddmode },
889 { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
890 { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
891 { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
892 { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
893 { { "get", "data", NULL }, handle_getdata, "Gets data on a channel", usage_getdata },
894 { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
895 { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
896 { { "set", "priority", NULL }, handle_setpriority, "Prioritizes the channel", usage_setpriority },
897 { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
898 { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
899 { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
900 { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
901 { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
902 { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus },
903 { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable },
904 { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable },
905 { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose },
906 { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget },
907 { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput },
908 { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel },
909 { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree }
912 static void join(char *s, int len, char *w[])
915 /* Join words into a string */
919 strncat(s, " ", len - strlen(s));
920 strncat(s, w[x], len - strlen(s));
924 static int help_workhorse(int fd, char *match[])
929 struct agi_command *e;
931 join(matchstr, sizeof(matchstr), match);
932 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
935 join(fullcmd, sizeof(fullcmd), e->cmda);
936 /* Hide commands that start with '_' */
937 if (fullcmd[0] == '_')
940 if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
944 ast_cli(fd, "%20.20s %s\n", fullcmd, e->summary);
949 static agi_command *find_command(char *cmds[], int exact)
954 for (x=0;x < sizeof(commands) / sizeof(commands[0]);x++) {
955 /* start optimistic */
957 for (y=0;match && cmds[y]; y++) {
958 /* If there are no more words in the command (and we're looking for
959 an exact match) or there is a difference between the two words,
960 then this is not a match */
961 if (!commands[x].cmda[y] && !exact)
963 if (strcasecmp(commands[x].cmda[y], cmds[y]))
966 /* If more words are needed to complete the command then this is not
967 a candidate (unless we're looking for a really inexact answer */
968 if ((exact > -1) && commands[x].cmda[y])
977 static int parse_args(char *s, int *max, char *argv[])
989 /* If it's escaped, put a literal quote */
994 if (quoted && whitespace) {
995 /* If we're starting a quote, coming off white space start a new word, too */
1003 if (!quoted && !escaped) {
1004 /* If we're not quoted, mark this as whitespace, and
1005 end the previous argument */
1009 /* Otherwise, just treat it as anything else */
1013 /* If we're escaped, print a literal, otherwise enable escaping */
1023 if (x >= MAX_ARGS -1) {
1024 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1027 /* Coming off of whitespace, start the next argument */
1036 /* Null terminate */
1043 static int agi_handle_command(struct ast_channel *chan, int fd, char *buf)
1045 char *argv[MAX_ARGS];
1050 parse_args(buf, &argc, argv);
1053 for (x=0;x<argc;x++)
1054 fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
1056 c = find_command(argv, 0);
1058 res = c->handler(chan, fd, argc, argv);
1060 case RESULT_SHOWUSAGE:
1061 fdprintf(fd, "520-Invalid command syntax. Proper usage follows:\n");
1062 fdprintf(fd, c->usage);
1063 fdprintf(fd, "520 End of proper usage.\n");
1065 case RESULT_FAILURE:
1066 /* They've already given the failure. We've been hung up on so handle this
1071 fdprintf(fd, "510 Invalid or unknown command\n");
1076 static int run_agi(struct ast_channel *chan, char *request, int *fds, int pid)
1078 struct ast_channel *c;
1081 int returnstatus = 0;
1082 struct ast_frame *f;
1085 if (!(readf = fdopen(fds[0], "r"))) {
1086 ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
1091 setup_env(chan, request, fds[1]);
1094 c = ast_waitfor_nandfds(&chan, 1, &fds[0], 1, NULL, &outfd, &ms);
1096 /* Idle the channel until we get a command */
1099 ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
1105 } else if (outfd > -1) {
1106 if (!fgets(buf, sizeof(buf), readf)) {
1107 /* Program terminated */
1110 if (option_verbose > 2)
1111 ast_verbose(VERBOSE_PREFIX_3 "AGI Script %s completed, returning %d\n", request, returnstatus);
1112 /* No need to kill the pid anymore, since they closed us */
1116 /* get rid of trailing newline, if any */
1117 if (*buf && buf[strlen(buf) - 1] == '\n')
1118 buf[strlen(buf) - 1] = 0;
1120 returnstatus |= agi_handle_command(chan, fds[1], buf);
1121 /* If the handle_command returns -1, we need to stop */
1122 if (returnstatus < 0) {
1126 ast_log(LOG_WARNING, "No channel, no fd?\n");
1131 /* Notify process */
1135 return returnstatus;
1138 static int handle_showagi(int fd, int argc, char *argv[]) {
1139 struct agi_command *e;
1142 return RESULT_SHOWUSAGE;
1144 e = find_command(argv + 2, 1);
1146 ast_cli(fd, e->usage);
1148 if (find_command(argv + 2, -1)) {
1149 return help_workhorse(fd, argv + 1);
1151 join(fullcmd, sizeof(fullcmd), argv+1);
1152 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1156 return help_workhorse(fd, NULL);
1158 return RESULT_SUCCESS;
1161 static int handle_dumpagihtml(int fd, int argc, char *argv[]) {
1162 struct agi_command *e;
1169 return RESULT_SHOWUSAGE;
1171 if (!(htmlfile = fopen(argv[2], "wt"))) {
1172 ast_cli(fd, "Could not create file '%s'\n", argv[2]);
1173 return RESULT_SHOWUSAGE;
1176 fprintf(htmlfile, "<HTML>\n<HEAD>\n<TITLE>AGI Commands</TITLE>\n</HEAD>\n");
1177 fprintf(htmlfile, "<BODY>\n<CENTER><B><H1>AGI Commands</H1></B></CENTER>\n\n");
1180 fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
1182 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
1186 join(fullcmd, sizeof(fullcmd), e->cmda);
1187 /* Hide commands that start with '_' */
1188 if (fullcmd[0] == '_')
1191 fprintf(htmlfile, "<TR><TD><TABLE BORDER=\"1\" CELLPADDING=\"5\" WIDTH=\"100%%\">\n");
1192 fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TD></TR>\n", fullcmd,e->summary);
1196 tempstr = strsep(&stringp, "\n");
1198 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">%s</TD></TR>\n", tempstr);
1200 fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
1201 while ((tempstr = strsep(&stringp, "\n")) != NULL) {
1202 fprintf(htmlfile, "%s<BR>\n",tempstr);
1205 fprintf(htmlfile, "</TD></TR>\n");
1206 fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
1210 fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
1212 ast_cli(fd, "AGI HTML Commands Dumped to: %s\n", argv[2]);
1213 return RESULT_SUCCESS;
1216 static int agi_exec(struct ast_channel *chan, void *data)
1219 struct localuser *u;
1225 if (!data || !strlen(data)) {
1226 ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
1231 strncpy(tmp, data, sizeof(tmp)-1);
1232 strsep(&stringp, "|");
1233 args = strsep(&stringp, "|");
1234 ringy = strsep(&stringp,"|");
1239 /* Answer if need be */
1240 if (chan->_state != AST_STATE_UP) {
1241 if (ringy) { /* if for ringing first */
1242 /* a little ringy-dingy first */
1243 ast_indicate(chan, AST_CONTROL_RINGING);
1246 if (ast_answer(chan)) {
1247 LOCAL_USER_REMOVE(u);
1252 res = launch_script(tmp, args, fds, &pid);
1254 res = run_agi(chan, tmp, fds, pid);
1258 LOCAL_USER_REMOVE(u);
1262 static char showagi_help[] =
1263 "Usage: show agi [topic]\n"
1264 " When called with a topic as an argument, displays usage\n"
1265 " information on the given command. If called without a\n"
1266 " topic, it provides a list of AGI commands.\n";
1269 static char dumpagihtml_help[] =
1270 "Usage: dump agihtml <filename>\n"
1271 " Dumps the agi command list in html format to given filename\n";
1273 struct ast_cli_entry showagi =
1274 { { "show", "agi", NULL }, handle_showagi, "Show AGI commands or specific help", showagi_help };
1276 struct ast_cli_entry dumpagihtml =
1277 { { "dump", "agihtml", NULL }, handle_dumpagihtml, "Dumps a list of agi command in html format", dumpagihtml_help };
1279 int unload_module(void)
1281 STANDARD_HANGUP_LOCALUSERS;
1282 ast_cli_unregister(&showagi);
1283 ast_cli_unregister(&dumpagihtml);
1284 return ast_unregister_application(app);
1287 int load_module(void)
1289 ast_cli_register(&showagi);
1290 ast_cli_register(&dumpagihtml);
1291 return ast_register_application(app, agi_exec, synopsis, descrip);
1294 char *description(void)
1302 STANDARD_USECOUNT(res);
1308 return ASTERISK_GPL_KEY;
1317 static int exp_lut[256] = {0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
1318 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
1319 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
1320 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
1321 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1322 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1323 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1324 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
1325 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1326 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1327 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1328 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1329 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1330 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1331 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
1332 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7};
1333 int sign, exponent, mantissa;
1334 unsigned char ulawbyte;
1336 /* Get the sample into sign-magnitude. */
1337 sign = (sample >> 8) & 0x80; /* set aside the sign */
1338 if (sign != 0) sample = -sample; /* get magnitude */
1339 if (sample > CLIP) sample = CLIP; /* clip the magnitude */
1341 /* Convert from 16 bit linear to ulaw. */
1342 sample = sample + BIAS;
1343 exponent = exp_lut[(sample >> 7) & 0xFF];
1344 mantissa = (sample >> (exponent + 3)) & 0x0F;
1345 ulawbyte = ~(sign | (exponent << 4) | mantissa);
1347 if (ulawbyte == 0) ulawbyte = 0x02; /* optional CCITT trap */