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";
76 #define TONE_BLOCK_SIZE 200
78 static float loudness = 8192.0;
80 unsigned char linear2ulaw(short sample);
81 static void make_tone_block(unsigned char *data, float f1, int *x);
83 static void make_tone_block(unsigned char *data, float f1, int *x)
88 for(i = 0; i < TONE_BLOCK_SIZE; i++)
90 val = loudness * sin((f1 * 2.0 * M_PI * (*x)++)/8000.0);
91 data[i] = linear2ulaw((int)val);
93 /* wrap back around from 8000 */
94 if (*x >= 8000) *x = 0;
98 static int launch_script(char *script, char *args, int *fds, int *opid)
105 if (script[0] != '/') {
106 snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_AGI_DIR, script);
110 ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
114 ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
121 ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
125 /* Redirect stdin and out */
126 dup2(fromast[0], STDIN_FILENO);
127 dup2(toast[1], STDOUT_FILENO);
128 /* Close everything but stdin/out/error */
129 for (x=STDERR_FILENO + 1;x<1024;x++)
132 execl(script, script, args, NULL);
133 /* Can't use ast_log since FD's are closed */
134 fprintf(stderr, "Failed to execute '%s': %s\n", script, strerror(errno));
137 if (option_verbose > 2)
138 ast_verbose(VERBOSE_PREFIX_3 "Launched AGI Script %s\n", script);
141 /* close what we're not using in the parent */
149 static void setup_env(struct ast_channel *chan, char *request, int fd)
151 /* Print initial environment, with agi_request always being the first
153 fdprintf(fd, "agi_request: %s\n", request);
154 fdprintf(fd, "agi_channel: %s\n", chan->name);
155 fdprintf(fd, "agi_language: %s\n", chan->language);
156 fdprintf(fd, "agi_type: %s\n", chan->type);
159 fdprintf(fd, "agi_callerid: %s\n", chan->callerid ? chan->callerid : "");
160 fdprintf(fd, "agi_dnid: %s\n", chan->dnid ? chan->dnid : "");
161 fdprintf(fd, "agi_rdnis: %s\n", chan->rdnis ? chan->rdnis : "");
163 /* Context information */
164 fdprintf(fd, "agi_context: %s\n", chan->context);
165 fdprintf(fd, "agi_extension: %s\n", chan->exten);
166 fdprintf(fd, "agi_priority: %d\n", chan->priority);
168 /* End with empty return */
172 static int handle_answer(struct ast_channel *chan, int fd, int argc, char *argv[])
176 if (chan->_state != AST_STATE_UP) {
177 /* Answer the chan */
178 res = ast_answer(chan);
180 fdprintf(fd, "200 result=%d\n", res);
182 return RESULT_SUCCESS;
184 return RESULT_FAILURE;
187 static int handle_waitfordigit(struct ast_channel *chan, int fd, int argc, char *argv[])
192 return RESULT_SHOWUSAGE;
193 if (sscanf(argv[3], "%i", &to) != 1)
194 return RESULT_SHOWUSAGE;
195 res = ast_waitfordigit(chan, to);
196 fdprintf(fd, "200 result=%d\n", res);
198 return RESULT_SUCCESS;
200 return RESULT_FAILURE;
203 static int handle_sendtext(struct ast_channel *chan, int fd, int argc, char *argv[])
207 return RESULT_SHOWUSAGE;
208 /* At the moment, the parser (perhaps broken) returns with
209 the last argument PLUS the newline at the end of the input
210 buffer. This probably needs to be fixed, but I wont do that
211 because other stuff may break as a result. The right way
212 would probably be to strip off the trailing newline before
213 parsing, then here, add a newline at the end of the string
214 before sending it to ast_sendtext --DUDE */
215 res = ast_sendtext(chan, argv[2]);
216 fdprintf(fd, "200 result=%d\n", res);
218 return RESULT_SUCCESS;
220 return RESULT_FAILURE;
223 static int handle_recvchar(struct ast_channel *chan, int fd, int argc, char *argv[])
227 return RESULT_SHOWUSAGE;
228 res = ast_recvchar(chan,atoi(argv[2]));
230 fdprintf(fd, "200 result=%d (timeout)\n", res);
231 return RESULT_SUCCESS;
234 fdprintf(fd, "200 result=%d\n", res);
235 return RESULT_SUCCESS;
238 fdprintf(fd, "200 result=%d (hangup)\n", res);
239 return RESULT_FAILURE;
243 static int handle_tddmode(struct ast_channel *chan, int fd, int argc, char *argv[])
247 return RESULT_SHOWUSAGE;
248 if (!strncasecmp(argv[2],"on",2)) x = 1; else x = 0;
249 if (!strncasecmp(argv[2],"mate",4)) x = 2;
250 if (!strncasecmp(argv[2],"tdd",3)) x = 1;
251 res = ast_channel_setoption(chan,AST_OPTION_TDD,&x,sizeof(char),0);
252 fdprintf(fd, "200 result=%d\n", res);
254 return RESULT_SUCCESS;
256 return RESULT_FAILURE;
259 static int handle_sendimage(struct ast_channel *chan, int fd, int argc, char *argv[])
263 return RESULT_SHOWUSAGE;
264 res = ast_send_image(chan, argv[2]);
265 if (!ast_check_hangup(chan))
267 fdprintf(fd, "200 result=%d\n", res);
269 return RESULT_SUCCESS;
271 return RESULT_FAILURE;
274 static int handle_streamfile(struct ast_channel *chan, int fd, int argc, char *argv[])
277 struct ast_filestream *fs;
278 long sample_offset = 0;
282 return RESULT_SHOWUSAGE;
284 return RESULT_SHOWUSAGE;
285 if ((argc > 4) && (sscanf(argv[4], "%ld", &sample_offset) != 1))
286 return RESULT_SHOWUSAGE;
288 fs = ast_openstream(chan, argv[2], chan->language);
290 fdprintf(fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
291 ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
292 return RESULT_FAILURE;
294 ast_seekstream(fs, 0, SEEK_END);
295 max_length = ast_tellstream(fs);
296 ast_seekstream(fs, sample_offset, SEEK_SET);
297 res = ast_applystream(chan, fs);
298 res = ast_playstream(fs);
300 fdprintf(fd, "200 result=%d endpos=%ld\n", res, sample_offset);
302 return RESULT_SHOWUSAGE;
304 return RESULT_FAILURE;
306 res = ast_waitstream(chan, argv[3]);
307 /* this is to check for if ast_waitstream closed the stream, we probably are at
308 * the end of the stream, return that amount, else check for the amount */
309 sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
310 ast_stopstream(chan);
311 fdprintf(fd, "200 result=%d endpos=%ld\n", res, sample_offset);
313 return RESULT_SUCCESS;
315 return RESULT_FAILURE;
318 static int handle_saynumber(struct ast_channel *chan, int fd, int argc, char *argv[])
323 return RESULT_SHOWUSAGE;
324 if (sscanf(argv[2], "%i", &num) != 1)
325 return RESULT_SHOWUSAGE;
326 res = ast_say_number(chan, num, argv[3], chan->language);
327 fdprintf(fd, "200 result=%d\n", res);
329 return RESULT_SUCCESS;
331 return RESULT_FAILURE;
334 static int handle_saydigits(struct ast_channel *chan, int fd, int argc, char *argv[])
339 return RESULT_SHOWUSAGE;
340 if (sscanf(argv[2], "%i", &num) != 1)
341 return RESULT_SHOWUSAGE;
342 res = ast_say_digit_str(chan, argv[2], argv[3], chan->language);
343 fdprintf(fd, "200 result=%d\n", res);
345 return RESULT_SUCCESS;
347 return RESULT_FAILURE;
350 int ast_app_getdata(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout);
352 static int handle_getdata(struct ast_channel *chan, int fd, int argc, char *argv[])
360 return RESULT_SHOWUSAGE;
361 if (argc >= 4) timeout = atoi(argv[3]); else timeout = 0;
362 if (argc >= 5) max = atoi(argv[4]); else max = 1024;
363 res = ast_app_getdata(chan, argv[2], data, max, timeout);
365 fdprintf(fd, "200 result=%s (timeout)\n", data);
367 fdprintf(fd, "200 result=%s\n", data);
369 return RESULT_SUCCESS;
371 return RESULT_FAILURE;
374 static int handle_setcontext(struct ast_channel *chan, int fd, int argc, char *argv[])
378 return RESULT_SHOWUSAGE;
379 strncpy(chan->context, argv[2], sizeof(chan->context)-1);
380 fdprintf(fd, "200 result=0\n");
381 return RESULT_SUCCESS;
384 static int handle_setextension(struct ast_channel *chan, int fd, int argc, char **argv)
387 return RESULT_SHOWUSAGE;
388 strncpy(chan->exten, argv[2], sizeof(chan->exten)-1);
389 fdprintf(fd, "200 result=0\n");
390 return RESULT_SUCCESS;
393 static int handle_setpriority(struct ast_channel *chan, int fd, int argc, char **argv)
397 return RESULT_SHOWUSAGE;
398 if (sscanf(argv[2], "%i", &pri) != 1)
399 return RESULT_SHOWUSAGE;
400 chan->priority = pri - 1;
401 fdprintf(fd, "200 result=0\n");
402 return RESULT_SUCCESS;
405 static int ms_diff(struct timeval *tv1, struct timeval *tv2)
409 ms = (tv1->tv_sec - tv2->tv_sec) * 1000;
410 ms += (tv1->tv_usec - tv2->tv_usec) / 1000;
414 static int handle_recordfile(struct ast_channel *chan, int fd, int argc, char *argv[])
416 struct ast_filestream *fs;
418 struct timeval tv, start;
419 long sample_offset = 0;
424 return RESULT_SHOWUSAGE;
425 if (sscanf(argv[5], "%i", &ms) != 1)
426 return RESULT_SHOWUSAGE;
427 /* backward compatibility, if no offset given, arg[6] would have been
428 * caught below and taken to be a beep, else if it is a digit then it is a
430 if ((argc >6) && (sscanf(argv[6], "%ld", &sample_offset) != 1))
431 res = ast_streamfile(chan, "beep", chan->language);
434 res = ast_streamfile(chan, "beep", chan->language);
436 res = ast_waitstream(chan, argv[4]);
438 fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY, 0, 0644);
441 fdprintf(fd, "200 result=%d (writefile)\n", res);
442 return RESULT_FAILURE;
446 ast_applystream(chan,fs);
447 /* really should have checks */
448 ast_seekstream(fs, sample_offset, SEEK_SET);
451 gettimeofday(&start, NULL);
452 gettimeofday(&tv, NULL);
453 while ((ms < 0) || (((tv.tv_sec - start.tv_sec) * 1000 + (tv.tv_usec - start.tv_usec)/1000) < ms)) {
454 res = ast_waitfor(chan, -1);
457 fdprintf(fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
458 return RESULT_FAILURE;
462 fdprintf(fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
464 return RESULT_FAILURE;
466 switch(f->frametype) {
468 if (strchr(argv[4], f->subclass)) {
469 /* This is an interrupting chracter */
470 sample_offset = ast_tellstream(fs);
471 fdprintf(fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
474 return RESULT_SUCCESS;
477 case AST_FRAME_VOICE:
478 ast_writestream(fs, f);
479 /* this is a safe place to check progress since we know that fs
480 * is valid after a write, and it will then have our current
482 sample_offset = ast_tellstream(fs);
486 gettimeofday(&tv, NULL);
488 fdprintf(fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
491 fdprintf(fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
492 return RESULT_SUCCESS;
495 static int handle_autohangup(struct ast_channel *chan, int fd, int argc, char *argv[])
500 return RESULT_SHOWUSAGE;
501 if (sscanf(argv[2], "%d", &timeout) != 1)
502 return RESULT_SHOWUSAGE;
506 chan->whentohangup = time(NULL) + timeout;
508 chan->whentohangup = 0;
509 fdprintf(fd, "200 result=0\n");
510 return RESULT_SUCCESS;
513 static int handle_hangup(struct ast_channel *chan, int fd, int argc, char **argv)
515 struct ast_channel *c;
517 /* no argument: hangup the current channel */
518 ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
519 fdprintf(fd, "200 result=1\n");
520 return RESULT_SUCCESS;
521 } else if (argc==2) {
522 /* one argument: look for info on the specified channel */
523 c = ast_channel_walk(NULL);
525 if (strcasecmp(argv[1],c->name)==0) {
526 /* we have a matching channel */
527 ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
528 fdprintf(fd, "200 result=1\n");
529 return RESULT_SUCCESS;
531 c = ast_channel_walk(c);
533 /* if we get this far no channel name matched the argument given */
534 fdprintf(fd, "200 result=-1\n");
535 return RESULT_SUCCESS;
537 return RESULT_SHOWUSAGE;
541 static int handle_exec(struct ast_channel *chan, int fd, int argc, char **argv)
547 return RESULT_SHOWUSAGE;
549 if (option_verbose > 2)
550 ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
552 app = pbx_findapp(argv[1]);
555 res = pbx_exec(chan, app, argv[2], 1);
557 ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
560 fdprintf(fd, "200 result=%d\n", res);
565 static int handle_setcallerid(struct ast_channel *chan, int fd, int argc, char **argv)
568 ast_set_callerid(chan, argv[2], 0);
570 /* strncpy(chan->callerid, argv[2], sizeof(chan->callerid)-1);
571 */ fdprintf(fd, "200 result=1\n");
572 return RESULT_SUCCESS;
575 static int handle_channelstatus(struct ast_channel *chan, int fd, int argc, char **argv)
577 struct ast_channel *c;
579 /* no argument: supply info on the current channel */
580 fdprintf(fd, "200 result=%d\n", chan->_state);
581 return RESULT_SUCCESS;
582 } else if (argc==3) {
583 /* one argument: look for info on the specified channel */
584 c = ast_channel_walk(NULL);
586 if (strcasecmp(argv[2],c->name)==0) {
587 fdprintf(fd, "200 result=%d\n", c->_state);
588 return RESULT_SUCCESS;
590 c = ast_channel_walk(c);
592 /* if we get this far no channel name matched the argument given */
593 fdprintf(fd, "200 result=-1\n");
594 return RESULT_SUCCESS;
596 return RESULT_SHOWUSAGE;
600 static int handle_setvariable(struct ast_channel *chan, int fd, int argc, char **argv)
603 pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
605 fdprintf(fd, "200 result=1\n");
606 return RESULT_SUCCESS;
609 static int handle_getvariable(struct ast_channel *chan, int fd, int argc, char **argv)
613 if ((tempstr = pbx_builtin_getvar_helper(chan, argv[2])) )
614 fdprintf(fd, "200 result=1 (%s)\n", tempstr);
616 fdprintf(fd, "200 result=0\n");
618 return RESULT_SUCCESS;
621 static int handle_verbose(struct ast_channel *chan, int fd, int argc, char **argv)
627 return RESULT_SHOWUSAGE;
630 sscanf(argv[2], "%d", &level);
634 prefix = VERBOSE_PREFIX_4;
637 prefix = VERBOSE_PREFIX_3;
640 prefix = VERBOSE_PREFIX_2;
644 prefix = VERBOSE_PREFIX_1;
648 if (level <= option_verbose)
649 ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
651 fdprintf(fd, "200 result=1\n");
653 return RESULT_SUCCESS;
656 static int handle_dbget(struct ast_channel *chan, int fd, int argc, char **argv)
661 return RESULT_SHOWUSAGE;
662 res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
664 fdprintf(fd, "200 result=0\n");
666 fdprintf(fd, "200 result=1 (%s)\n", tmp);
668 return RESULT_SUCCESS;
671 static int handle_dbput(struct ast_channel *chan, int fd, int argc, char **argv)
675 return RESULT_SHOWUSAGE;
676 res = ast_db_put(argv[2], argv[3], argv[4]);
678 fdprintf(fd, "200 result=0\n");
680 fdprintf(fd, "200 result=1\n");
682 return RESULT_SUCCESS;
685 static int handle_dbdel(struct ast_channel *chan, int fd, int argc, char **argv)
689 return RESULT_SHOWUSAGE;
690 res = ast_db_del(argv[2], argv[3]);
692 fdprintf(fd, "200 result=0\n");
694 fdprintf(fd, "200 result=1\n");
696 return RESULT_SUCCESS;
699 static int handle_dbdeltree(struct ast_channel *chan, int fd, int argc, char **argv)
702 if ((argc < 3) || (argc > 4))
703 return RESULT_SHOWUSAGE;
705 res = ast_db_deltree(argv[2], argv[3]);
707 res = ast_db_deltree(argv[2], NULL);
710 fdprintf(fd, "200 result=0\n");
712 fdprintf(fd, "200 result=1\n");
713 return RESULT_SUCCESS;
716 static char usage_dbput[] =
717 " Usage: DATABASE PUT <family> <key> <value>\n"
718 " Adds or updates an entry in the Asterisk database for a\n"
719 " given family, key, and value.\n"
720 " Returns 1 if succesful, 0 otherwise\n";
722 static char usage_dbget[] =
723 " Usage: DATABASE GET <family> <key>\n"
724 " Retrieves an entry in the Asterisk database for a\n"
725 " given family and key.\n"
726 " Returns 0 if <key> is not set. Returns 1 if <key>\n"
727 " is set and returns the variable in parenthesis\n"
728 " example return code: 200 result=1 (testvariable)\n";
730 static char usage_dbdel[] =
731 " Usage: DATABASE DEL <family> <key>\n"
732 " Deletes an entry in the Asterisk database for a\n"
733 " given family and key.\n"
734 " Returns 1 if succesful, 0 otherwise\n";
736 static char usage_dbdeltree[] =
737 " Usage: DATABASE DELTREE <family> [keytree]\n"
738 " Deletes a family or specific keytree withing a family\n"
739 " in the Asterisk database.\n"
740 " Returns 1 if succesful, 0 otherwise\n";
742 static char usage_verbose[] =
743 " Usage: VERBOSE <message> <level>\n"
744 " Sends <message> to the console via verbose message system.\n"
745 " <level> is the the verbose level (1-4)\n"
746 " Always returns 1\n";
748 static char usage_getvariable[] =
749 " Usage: GET VARIABLE <variablename>\n"
750 " Returns 0 if <variablename> is not set. Returns 1 if <variablename>\n"
751 " is set and returns the variable in parenthesis\n"
752 " example return code: 200 result=1 (testvariable)\n";
754 static char usage_setvariable[] =
755 " Usage: SET VARIABLE <variablename> <value>\n";
757 static char usage_channelstatus[] =
758 " Usage: CHANNEL STATUS [<channelname>]\n"
759 " Returns the status of the specified channel.\n"
760 " If no channel name is given the returns the status of the\n"
761 " current channel.\n"
763 " 0 Channel is down and available\n"
764 " 1 Channel is down, but reserved\n"
765 " 2 Channel is off hook\n"
766 " 3 Digits (or equivalent) have been dialed\n"
767 " 4 Line is ringing\n"
768 " 5 Remote end is ringing\n"
772 static char usage_setcallerid[] =
773 " Usage: SET CALLERID <number>\n"
774 " Changes the callerid of the current channel.\n";
776 static char usage_exec[] =
777 " Usage: EXEC <application> <options>\n"
778 " Executes <application> with given <options>.\n"
779 " Returns whatever the application returns, or -2 on failure to find application\n";
781 static char usage_hangup[] =
782 " Usage: HANGUP [<channelname>]\n"
783 " Hangs up the specified channel.\n"
784 " If no channel name is given, hangs up the current channel\n";
786 static char usage_answer[] =
788 " Answers channel if not already in answer state. Returns -1 on\n"
789 " channel failure, or 0 if successful.\n";
791 static char usage_waitfordigit[] =
792 " Usage: WAIT FOR DIGIT <timeout>\n"
793 " Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
794 " Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
795 " the numerical value of the ascii of the digit if one is received. Use -1\n"
796 " for the timeout value if you desire the call to block indefinitely.\n";
798 static char usage_sendtext[] =
799 " Usage: SEND TEXT \"<text to send>\"\n"
800 " Sends the given text on a channel. Most channels do not support the\n"
801 " transmission of text. Returns 0 if text is sent, or if the channel does not\n"
802 " support text transmission. Returns -1 only on error/hangup. Text\n"
803 " consisting of greater than one word should be placed in quotes since the\n"
804 " command only accepts a single argument.\n";
806 static char usage_recvchar[] =
807 " Usage: RECEIVE CHAR <timeout>\n"
808 " Receives a character of text on a channel. Specify timeout to be the\n"
809 " maximum time to wait for input in milliseconds, or 0 for infinite. Most channels\n"
810 " do not support the reception of text. Returns the decimal value of the character\n"
811 " if one is received, or 0 if the channel does not support text reception. Returns\n"
812 " -1 only on error/hangup.\n";
814 static char usage_tddmode[] =
815 " Usage: TDD MODE <on|off>\n"
816 " Enable/Disable TDD transmission/reception on a channel. Returns 1 if\n"
817 " successful, or 0 if channel is not TDD-capable.\n";
819 static char usage_sendimage[] =
820 " Usage: SEND IMAGE <image>\n"
821 " Sends the given image on a channel. Most channels do not support the\n"
822 " transmission of images. Returns 0 if image is sent, or if the channel does not\n"
823 " support image transmission. Returns -1 only on error/hangup. Image names\n"
824 " should not include extensions.\n";
826 static char usage_streamfile[] =
827 " Usage: STREAM FILE <filename> <escape digits> [sample offset]\n"
828 " Send the given file, allowing playback to be interrupted by the given\n"
829 " digits, if any. Use double quotes for the digits if you wish none to be\n"
830 " permitted. If sample offset is provided then the audio will seek to sample\n"
831 " offset before play starts. Returns 0 if playback completes without a digit\n"
832 " being pressed, or the ASCII numerical value of the digit if one was pressed,\n"
833 " or -1 on error or if the channel was disconnected. Remember, the file\n"
834 " extension must not be included in the filename.\n";
836 static char usage_saynumber[] =
837 " Usage: SAY NUMBER <number> <escape digits>\n"
838 " Say a given number, returning early if any of the given DTMF digits\n"
839 " are received on the channel. Returns 0 if playback completes without a digit\n"
840 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
841 " -1 on error/hangup.\n";
843 static char usage_saydigits[] =
844 " Usage: SAY DIGITS <number> <escape digits>\n"
845 " Say a given digit string, returning early if any of the given DTMF digits\n"
846 " are received on the channel. Returns 0 if playback completes without a digit\n"
847 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
848 " -1 on error/hangup.\n";
850 static char usage_getdata[] =
851 " Usage: GET DATA <file to be streamed> [timeout] [max digits]\n"
852 " Stream the given file, and recieve DTMF data. Returns the digits recieved\n"
853 "from the channel at the other end.\n";
855 static char usage_setcontext[] =
856 " Usage: SET CONTEXT <desired context>\n"
857 " Sets the context for continuation upon exiting the application.\n";
859 static char usage_setextension[] =
860 " Usage: SET EXTENSION <new extension>\n"
861 " Changes the extension for continuation upon exiting the application.\n";
863 static char usage_setpriority[] =
864 " Usage: SET PRIORITY <num>\n"
865 " Changes the priority for continuation upon exiting the application.\n";
867 static char usage_recordfile[] =
868 " Usage: RECORD FILE <filename> <format> <escape digits> <timeout> [offset samples] [BEEP]\n"
869 " Record to a file until a given dtmf digit in the sequence is received\n"
870 " Returns -1 on hangup or error. The format will specify what kind of file\n"
871 " will be recorded. The timeout is the maximum record time in milliseconds, or\n"
872 " -1 for no timeout. Offset samples is optional, and if provided will seek to\n"
873 " the offset without exceeding the end of the file\n";
875 static char usage_autohangup[] =
876 " Usage: SET AUTOHANGUP <time>\n"
877 " Cause the channel to automatically hangup at <time> seconds in the\n"
878 "future. Of course it can be hungup before then as well. Setting to\n"
879 "0 will cause the autohangup feature to be disabled on this channel.\n";
881 agi_command commands[] = {
882 { { "answer", NULL }, handle_answer, "Asserts answer", usage_answer },
883 { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
884 { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
885 { { "receive", "char", NULL }, handle_recvchar, "Receives text from channels supporting it", usage_recvchar },
886 { { "tdd", "mode", NULL }, handle_tddmode, "Sends text to channels supporting it", usage_tddmode },
887 { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
888 { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
889 { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
890 { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
891 { { "get", "data", NULL }, handle_getdata, "Gets data on a channel", usage_getdata },
892 { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
893 { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
894 { { "set", "priority", NULL }, handle_setpriority, "Prioritizes the channel", usage_setpriority },
895 { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
896 { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
897 { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
898 { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
899 { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
900 { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus },
901 { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable },
902 { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable },
903 { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose },
904 { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget },
905 { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput },
906 { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel },
907 { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree }
910 static void join(char *s, int len, char *w[])
913 /* Join words into a string */
917 strncat(s, " ", len - strlen(s));
918 strncat(s, w[x], len - strlen(s));
922 static int help_workhorse(int fd, char *match[])
927 struct agi_command *e;
929 join(matchstr, sizeof(matchstr), match);
930 for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
933 join(fullcmd, sizeof(fullcmd), e->cmda);
934 /* Hide commands that start with '_' */
935 if (fullcmd[0] == '_')
938 if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
942 ast_cli(fd, "%20.20s %s\n", fullcmd, e->summary);
947 static agi_command *find_command(char *cmds[], int exact)
952 for (x=0;x < sizeof(commands) / sizeof(commands[0]);x++) {
953 /* start optimistic */
955 for (y=0;match && cmds[y]; y++) {
956 /* If there are no more words in the command (and we're looking for
957 an exact match) or there is a difference between the two words,
958 then this is not a match */
959 if (!commands[x].cmda[y] && !exact)
961 /* don't segfault if the next part of a command doesn't exist */
962 if (!commands[x].cmda[y]) return NULL;
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 */