include "logger.h" and errno.h from asterisk.h - usage shows that they
[asterisk/asterisk.git] / res / res_agi.c
index 0b88b89..d8df079 100644 (file)
  * \author Mark Spencer <markster@digium.com> 
  */
 
-#include <sys/types.h>
-#include <netdb.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <arpa/inet.h>
+#include "asterisk.h"
+
+ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+
 #include <math.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
 #include <signal.h>
 #include <sys/time.h>
-#include <stdio.h>
 #include <fcntl.h>
-#include <errno.h>
-
-#include "asterisk.h"
-
-ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+#include <sys/wait.h>
+#include <sys/stat.h>
 
+#include "asterisk/network.h"
 #include "asterisk/file.h"
-#include "asterisk/logger.h"
 #include "asterisk/channel.h"
 #include "asterisk/pbx.h"
 #include "asterisk/module.h"
 #include "asterisk/astdb.h"
 #include "asterisk/callerid.h"
 #include "asterisk/cli.h"
-#include "asterisk/logger.h"
 #include "asterisk/options.h"
 #include "asterisk/image.h"
 #include "asterisk/say.h"
 #include "asterisk/app.h"
 #include "asterisk/dsp.h"
 #include "asterisk/musiconhold.h"
-#include "asterisk/manager.h"
 #include "asterisk/utils.h"
 #include "asterisk/lock.h"
 #include "asterisk/strings.h"
 #include "asterisk/agi.h"
 
 #define MAX_ARGS 128
-#define MAX_COMMANDS 128
-
-/* Recycle some stuff from the CLI interface */
-#define fdprintf agi_debug_cli
+#define AGI_NANDFS_RETRY 3
+#define AGI_BUF_LEN 2048
 
 static char *app = "AGI";
 
@@ -82,21 +68,26 @@ static char *esynopsis = "Executes an EAGI compliant application";
 static char *deadsynopsis = "Executes AGI on a hungup channel";
 
 static char *descrip =
-"  [E|Dead]AGI(command|args): Executes an Asterisk Gateway Interface compliant\n"
+"  [E|Dead]AGI(command,args): Executes an Asterisk Gateway Interface compliant\n"
 "program on a channel. AGI allows Asterisk to launch external programs\n"
 "written in any language to control a telephony channel, play audio,\n"
 "read DTMF digits, etc. by communicating with the AGI protocol on stdin\n"
 "and stdout.\n"
-"Returns -1 on hangup (except for DeadAGI) or if application requested\n"
-" hangup, or 0 on non-hangup exit. \n"
-"Using 'EAGI' provides enhanced AGI, with incoming audio available out of band\n"
+"  This channel will stop dialplan execution on hangup inside of this\n"
+"application, except when using DeadAGI.  Otherwise, dialplan execution\n"
+"will continue normally.\n"
+"  A locally executed AGI script will receive SIGHUP on hangup from the channel\n"
+"except when using DeadAGI. This can be disabled by setting the AGISIGHUP channel\n"
+"variable to \"no\" before executing the AGI application.\n"
+"  Using 'EAGI' provides enhanced AGI, with incoming audio available out of band\n"
 "on file descriptor 3\n\n"
-"Use the CLI command 'show agi' to list available agi commands\n";
+"  Use the CLI command 'agi show' to list available agi commands\n"
+"  This application sets the following channel variable upon completion:\n"
+"     AGISTATUS      The status of the attempt to the run the AGI script\n"
+"                    text string, one of SUCCESS | FAILED | NOTFOUND | HANGUP\n";
 
 static int agidebug = 0;
 
-struct module_symbols *me;
-
 #define TONE_BLOCK_SIZE 200
 
 /* Max time to connect to an AGI remote host */
@@ -104,43 +95,61 @@ struct module_symbols *me;
 
 #define AGI_PORT 4573
 
-static void agi_debug_cli(int fd, char *fmt, ...)
+enum agi_result {
+       AGI_RESULT_SUCCESS,
+       AGI_RESULT_SUCCESS_FAST,
+       AGI_RESULT_FAILURE,
+       AGI_RESULT_NOTFOUND,
+       AGI_RESULT_HANGUP,
+};
+
+static agi_command *find_command(char *cmds[], int exact);
+
+AST_THREADSTORAGE(agi_buf);
+#define AGI_BUF_INITSIZE 256
+
+int ast_agi_fdprintf(struct ast_channel *chan, int fd, char *fmt, ...)
 {
-       char *stuff;
        int res = 0;
-
        va_list ap;
+       struct ast_str *buf;
+
+       if (!(buf = ast_str_thread_get(&agi_buf, AGI_BUF_INITSIZE)))
+               return -1;
+
        va_start(ap, fmt);
-       res = vasprintf(&stuff, fmt, ap);
+       res = ast_str_set_va(&buf, 0, fmt, ap);
        va_end(ap);
+
        if (res == -1) {
                ast_log(LOG_ERROR, "Out of memory\n");
-       } else {
-               if (agidebug)
-                       ast_verbose("AGI Tx >> %s", stuff);
-               ast_carefulwrite(fd, stuff, strlen(stuff), 100);
-               free(stuff);
+               return -1;
        }
+
+       if (agidebug) {
+               if (chan) {
+                       ast_verbose("<%s>AGI Tx >> %s", chan->name, buf->str);
+               } else {
+                       ast_verbose("AGI Tx >> %s", buf->str);
+               }
+       }
+
+       return ast_carefulwrite(fd, buf->str, buf->used, 100);
 }
 
 /* launch_netscript: The fastagi handler.
        FastAGI defaults to port 4573 */
-static int launch_netscript(char *agiurl, char *argv[], int *fds, int *efd, int *opid)
+static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds, int *efd, int *opid)
 {
-       int s;
-       int flags;
+       int s, flags, res, port = AGI_PORT;
        struct pollfd pfds[1];
-       char *host;
-       char *c; int port = AGI_PORT;
-       char *script="";
+       char *host, *c, *script = "";
        struct sockaddr_in sin;
        struct hostent *hp;
        struct ast_hostent ahp;
 
        /* agiusl is "agi://host.domain[:port][/script/name]" */
        host = ast_strdupa(agiurl + 6); /* Remove agi:// */
-       if (!host)
-               return -1;
        /* Strip off any script name */
        if ((c = strchr(host, '/'))) {
                *c = '\0';
@@ -156,18 +165,15 @@ static int launch_netscript(char *agiurl, char *argv[], int *fds, int *efd, int
                ast_log(LOG_WARNING, "AGI URI's don't support Enhanced AGI yet\n");
                return -1;
        }
-       hp = ast_gethostbyname(host, &ahp);
-       if (!hp) {
+       if (!(hp = ast_gethostbyname(host, &ahp))) {
                ast_log(LOG_WARNING, "Unable to locate host '%s'\n", host);
                return -1;
        }
-       s = socket(AF_INET, SOCK_STREAM, 0);
-       if (s < 0) {
+       if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
                ast_log(LOG_WARNING, "Unable to create socket: %s\n", strerror(errno));
                return -1;
        }
-       flags = fcntl(s, F_GETFL);
-       if (flags < 0) {
+       if ((flags = fcntl(s, F_GETFL)) < 0) {
                ast_log(LOG_WARNING, "Fcntl(F_GETFL) failed: %s\n", strerror(errno));
                close(s);
                return -1;
@@ -184,66 +190,73 @@ static int launch_netscript(char *agiurl, char *argv[], int *fds, int *efd, int
        if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) && (errno != EINPROGRESS)) {
                ast_log(LOG_WARNING, "Connect failed with unexpected error: %s\n", strerror(errno));
                close(s);
-               return -1;
+               return AGI_RESULT_FAILURE;
        }
 
        pfds[0].fd = s;
        pfds[0].events = POLLOUT;
-       while (poll(pfds, 1, MAX_AGI_CONNECT) != 1) {
+       while ((res = poll(pfds, 1, MAX_AGI_CONNECT)) != 1) {
                if (errno != EINTR) {
-                       ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
+                       if (!res) {
+                               ast_log(LOG_WARNING, "FastAGI connection to '%s' timed out after MAX_AGI_CONNECT (%d) milliseconds.\n",
+                                       agiurl, MAX_AGI_CONNECT);
+                       } else
+                               ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
                        close(s);
-                       return -1;
+                       return AGI_RESULT_FAILURE;
                }
        }
-       /* XXX in theory should check for partial writes... */
-       while (write(s, "agi_network: yes\n", strlen("agi_network: yes\n")) < 0) {
+
+       if (ast_agi_fdprintf(NULL, s, "agi_network: yes\n") < 0) {
                if (errno != EINTR) {
                        ast_log(LOG_WARNING, "Connect to '%s' failed: %s\n", agiurl, strerror(errno));
                        close(s);
-                       return -1;
+                       return AGI_RESULT_FAILURE;
                }
        }
 
        /* If we have a script parameter, relay it to the fastagi server */
+       /* Script parameters take the form of: AGI(agi://my.example.com/?extension=${EXTEN}) */
        if (!ast_strlen_zero(script))
-               fdprintf(s, "agi_network_script: %s\n", script);
+               ast_agi_fdprintf(NULL, s, "agi_network_script: %s\n", script);
 
-       if (option_debug > 3)
-               ast_log(LOG_DEBUG, "Wow, connected!\n");
+       ast_debug(4, "Wow, connected!\n");
        fds[0] = s;
        fds[1] = s;
        *opid = -1;
-       return 0;
+       return AGI_RESULT_SUCCESS_FAST;
 }
 
-static int launch_script(char *script, char *argv[], int *fds, int *efd, int *opid)
+static enum agi_result launch_script(char *script, char *argv[], int *fds, int *efd, int *opid)
 {
        char tmp[256];
-       int pid;
-       int toast[2];
-       int fromast[2];
-       int audio[2];
-       int x;
-       int res;
-       sigset_t signal_set;
-       
+       int pid, toast[2], fromast[2], audio[2], x, res;
+       sigset_t signal_set, old_set;
+       struct stat st;
+
        if (!strncasecmp(script, "agi://", 6))
                return launch_netscript(script, argv, fds, efd, opid);
        
        if (script[0] != '/') {
-               snprintf(tmp, sizeof(tmp), "%s/%s", (char *)ast_config_AST_AGI_DIR, script);
+               snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_AGI_DIR, script);
                script = tmp;
        }
+
+       /* Before even trying let's see if the file actually exists */
+       if (stat(script, &st)) {
+               ast_log(LOG_WARNING, "Failed to execute '%s': File does not exist.\n", script);
+               return AGI_RESULT_NOTFOUND;
+       }
+
        if (pipe(toast)) {
                ast_log(LOG_WARNING, "Unable to create toast pipe: %s\n",strerror(errno));
-               return -1;
+               return AGI_RESULT_FAILURE;
        }
        if (pipe(fromast)) {
                ast_log(LOG_WARNING, "unable to create fromast pipe: %s\n", strerror(errno));
                close(toast[0]);
                close(toast[1]);
-               return -1;
+               return AGI_RESULT_FAILURE;
        }
        if (efd) {
                if (pipe(audio)) {
@@ -252,7 +265,7 @@ static int launch_script(char *script, char *argv[], int *fds, int *efd, int *op
                        close(fromast[1]);
                        close(toast[0]);
                        close(toast[1]);
-                       return -1;
+                       return AGI_RESULT_FAILURE;
                }
                res = fcntl(audio[1], F_GETFL);
                if (res > -1) 
@@ -265,13 +278,17 @@ static int launch_script(char *script, char *argv[], int *fds, int *efd, int *op
                        close(toast[1]);
                        close(audio[0]);
                        close(audio[1]);
-                       return -1;
+                       return AGI_RESULT_FAILURE;
                }
        }
-       pid = fork();
-       if (pid < 0) {
+
+       /* Block SIGHUP during the fork - prevents a race */
+       sigfillset(&signal_set);
+       pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
+       if ((pid = fork()) < 0) {
                ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
-               return -1;
+               pthread_sigmask(SIG_SETMASK, &old_set, NULL);
+               return AGI_RESULT_FAILURE;
        }
        if (!pid) {
                /* Pass paths to AGI via environmental variables */
@@ -287,119 +304,133 @@ static int launch_script(char *script, char *argv[], int *fds, int *efd, int *op
                setenv("AST_KEY_DIR", ast_config_AST_KEY_DIR, 1);
                setenv("AST_RUN_DIR", ast_config_AST_RUN_DIR, 1);
 
+               /* Don't run AGI scripts with realtime priority -- it causes audio stutter */
+               ast_set_priority(0);
+
                /* Redirect stdin and out, provide enhanced audio channel if desired */
                dup2(fromast[0], STDIN_FILENO);
                dup2(toast[1], STDOUT_FILENO);
-               if (efd) {
+               if (efd)
                        dup2(audio[0], STDERR_FILENO + 1);
-               } else {
+               else
                        close(STDERR_FILENO + 1);
-               }
-               
+
+               /* Before we unblock our signals, return our trapped signals back to the defaults */
+               signal(SIGHUP, SIG_DFL);
+               signal(SIGCHLD, SIG_DFL);
+               signal(SIGINT, SIG_DFL);
+               signal(SIGURG, SIG_DFL);
+               signal(SIGTERM, SIG_DFL);
+               signal(SIGPIPE, SIG_DFL);
+               signal(SIGXFSZ, SIG_DFL);
+
                /* unblock important signal handlers */
-               if (sigfillset(&signal_set) || pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
+               if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
                        ast_log(LOG_WARNING, "unable to unblock signals for AGI script: %s\n", strerror(errno));
-                       exit(1);
+                       _exit(1);
                }
 
                /* Close everything but stdin/out/error */
-               for (x=STDERR_FILENO + 2;x<1024;x++) 
+               for (x = STDERR_FILENO + 2; x < 1024; x++) 
                        close(x);
 
-               /* Don't run AGI scripts with realtime priority -- it causes audio stutter */
-               ast_set_priority(0);
-
                /* Execute script */
+               /* XXX argv should be deprecated in favor of passing agi_argX paramaters */
                execv(script, argv);
                /* Can't use ast_log since FD's are closed */
                fprintf(stdout, "verbose \"Failed to execute '%s': %s\" 2\n", script, strerror(errno));
                fflush(stdout);
-               exit(1);
+               _exit(1);
        }
-       if (option_verbose > 2) 
-               ast_verbose(VERBOSE_PREFIX_3 "Launched AGI Script %s\n", script);
+       pthread_sigmask(SIG_SETMASK, &old_set, NULL);
+       ast_verb(3, "Launched AGI Script %s\n", script);
        fds[0] = toast[0];
        fds[1] = fromast[1];
-       if (efd) {
+       if (efd)
                *efd = audio[1];
-       }
        /* close what we're not using in the parent */
        close(toast[1]);
        close(fromast[0]);
 
-       if (efd) {
-               /* [PHM 12/18/03] */
+       if (efd)
                close(audio[0]);
-       }
 
        *opid = pid;
-       return 0;
-               
+       return AGI_RESULT_SUCCESS;
 }
 
-static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced)
+static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[])
 {
+       int count;
+
        /* Print initial environment, with agi_request always being the first
           thing */
-       fdprintf(fd, "agi_request: %s\n", request);
-       fdprintf(fd, "agi_channel: %s\n", chan->name);
-       fdprintf(fd, "agi_language: %s\n", chan->language);
-       fdprintf(fd, "agi_type: %s\n", chan->tech->type);
-       fdprintf(fd, "agi_uniqueid: %s\n", chan->uniqueid);
+       ast_agi_fdprintf(chan, fd, "agi_request: %s\n", request);
+       ast_agi_fdprintf(chan, fd, "agi_channel: %s\n", chan->name);
+       ast_agi_fdprintf(chan, fd, "agi_language: %s\n", chan->language);
+       ast_agi_fdprintf(chan, fd, "agi_type: %s\n", chan->tech->type);
+       ast_agi_fdprintf(chan, fd, "agi_uniqueid: %s\n", chan->uniqueid);
 
        /* ANI/DNIS */
-       fdprintf(fd, "agi_callerid: %s\n", S_OR(chan->cid.cid_num, "unknown"));
-       fdprintf(fd, "agi_calleridname: %s\n", S_OR(chan->cid.cid_name, "unknown"));
-       fdprintf(fd, "agi_callingpres: %d\n", chan->cid.cid_pres);
-       fdprintf(fd, "agi_callingani2: %d\n", chan->cid.cid_ani2);
-       fdprintf(fd, "agi_callington: %d\n", chan->cid.cid_ton);
-       fdprintf(fd, "agi_callingtns: %d\n", chan->cid.cid_tns);
-       fdprintf(fd, "agi_dnid: %s\n", S_OR(chan->cid.cid_dnid, "unknown"));
-       fdprintf(fd, "agi_rdnis: %s\n", S_OR(chan->cid.cid_rdnis, "unknown"));
+       ast_agi_fdprintf(chan, fd, "agi_callerid: %s\n", S_OR(chan->cid.cid_num, "unknown"));
+       ast_agi_fdprintf(chan, fd, "agi_calleridname: %s\n", S_OR(chan->cid.cid_name, "unknown"));
+       ast_agi_fdprintf(chan, fd, "agi_callingpres: %d\n", chan->cid.cid_pres);
+       ast_agi_fdprintf(chan, fd, "agi_callingani2: %d\n", chan->cid.cid_ani2);
+       ast_agi_fdprintf(chan, fd, "agi_callington: %d\n", chan->cid.cid_ton);
+       ast_agi_fdprintf(chan, fd, "agi_callingtns: %d\n", chan->cid.cid_tns);
+       ast_agi_fdprintf(chan, fd, "agi_dnid: %s\n", S_OR(chan->cid.cid_dnid, "unknown"));
+       ast_agi_fdprintf(chan, fd, "agi_rdnis: %s\n", S_OR(chan->cid.cid_rdnis, "unknown"));
 
        /* Context information */
-       fdprintf(fd, "agi_context: %s\n", chan->context);
-       fdprintf(fd, "agi_extension: %s\n", chan->exten);
-       fdprintf(fd, "agi_priority: %d\n", chan->priority);
-       fdprintf(fd, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
+       ast_agi_fdprintf(chan, fd, "agi_context: %s\n", chan->context);
+       ast_agi_fdprintf(chan, fd, "agi_extension: %s\n", chan->exten);
+       ast_agi_fdprintf(chan, fd, "agi_priority: %d\n", chan->priority);
+       ast_agi_fdprintf(chan, fd, "agi_enhanced: %s\n", enhanced ? "1.0" : "0.0");
 
        /* User information */
-       fdprintf(fd, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
-    
+       ast_agi_fdprintf(chan, fd, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
+
+       /* Send any parameters to the fastagi server that have been passed via the agi application */
+       /* Agi application paramaters take the form of: AGI(/path/to/example/script|${EXTEN}) */
+       for(count = 1; count < argc; count++)
+               ast_agi_fdprintf(chan, fd, "agi_arg_%d: %s\n", count, argv[count]);
+
        /* End with empty return */
-       fdprintf(fd, "\n");
+       ast_agi_fdprintf(chan, fd, "\n");
 }
 
 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res;
-       res = 0;
-       if (chan->_state != AST_STATE_UP) {
-               /* Answer the chan */
+       int res = 0;
+
+       /* Answer the channel */
+       if (chan->_state != AST_STATE_UP)
                res = ast_answer(chan);
-       }
-       fdprintf(agi->fd, "200 result=%d\n", res);
+
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res;
-       int to;
+       int res, to;
+
        if (argc != 4)
                return RESULT_SHOWUSAGE;
        if (sscanf(argv[3], "%d", &to) != 1)
                return RESULT_SHOWUSAGE;
        res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
        int res;
+
        if (argc != 3)
                return RESULT_SHOWUSAGE;
+
        /* At the moment, the parser (perhaps broken) returns with
           the last argument PLUS the newline at the end of the input
           buffer. This probably needs to be fixed, but I wont do that
@@ -408,26 +439,28 @@ static int handle_sendtext(struct ast_channel *chan, AGI *agi, int argc, char *a
           parsing, then here, add a newline at the end of the string
           before sending it to ast_sendtext --DUDE */
        res = ast_sendtext(chan, argv[2]);
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
        int res;
+
        if (argc != 3)
                return RESULT_SHOWUSAGE;
+
        res = ast_recvchar(chan,atoi(argv[2]));
        if (res == 0) {
-               fdprintf(agi->fd, "200 result=%d (timeout)\n", res);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d (timeout)\n", res);
                return RESULT_SUCCESS;
        }
        if (res > 0) {
-               fdprintf(agi->fd, "200 result=%d\n", res);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
                return RESULT_SUCCESS;
        }
        else {
-               fdprintf(agi->fd, "200 result=%d (hangup)\n", res);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d (hangup)\n", res);
                return RESULT_FAILURE;
        }
 }
@@ -438,21 +471,24 @@ static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, char *a
        
        if (argc != 3)
                return RESULT_SHOWUSAGE;
+
        buf = ast_recvtext(chan,atoi(argv[2]));
        if (buf) {
-               fdprintf(agi->fd, "200 result=1 (%s)\n", buf);
-               free(buf);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s)\n", buf);
+               ast_free(buf);
        } else {        
-               fdprintf(agi->fd, "200 result=-1\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=-1\n");
        }
        return RESULT_SUCCESS;
 }
 
 static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res,x;
+       int res, x;
+
        if (argc != 3)
                return RESULT_SHOWUSAGE;
+
        if (!strncasecmp(argv[2],"on",2)) 
                x = 1; 
        else 
@@ -463,32 +499,30 @@ static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, char *ar
                x = 1;
        res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
        if (res != RESULT_SUCCESS)
-               fdprintf(agi->fd, "200 result=0\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        else
-               fdprintf(agi->fd, "200 result=1\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
        return RESULT_SUCCESS;
 }
 
 static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
        int res;
+
        if (argc != 3)
                return RESULT_SHOWUSAGE;
+
        res = ast_send_image(chan, argv[2]);
        if (!ast_check_hangup(chan))
                res = 0;
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res = 0;
-       int skipms = 3000;
-       char *fwd = NULL;
-       char *rev = NULL;
-       char *pause = NULL;
-       char *stop = NULL;
+       int res = 0, skipms = 3000;
+       char *fwd = NULL, *rev = NULL, *pause = NULL, *stop = NULL;
 
        if (argc < 5 || argc > 9)
                return RESULT_SHOWUSAGE;
@@ -501,12 +535,12 @@ static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc
        if ((argc > 5) && (sscanf(argv[5], "%d", &skipms) != 1))
                return RESULT_SHOWUSAGE;
 
-       if (argc > 6 && !ast_strlen_zero(argv[8]))
+       if (argc > 6 && !ast_strlen_zero(argv[6]))
                fwd = argv[6];
        else
                fwd = "#";
 
-       if (argc > 7 && !ast_strlen_zero(argv[8]))
+       if (argc > 7 && !ast_strlen_zero(argv[7]))
                rev = argv[7];
        else
                rev = "*";
@@ -516,39 +550,49 @@ static int handle_controlstreamfile(struct ast_channel *chan, AGI *agi, int argc
        else
                pause = NULL;
        
-       res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, pause, NULL, skipms);
+       res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, pause, NULL, skipms, NULL);
        
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
 
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res;
-       struct ast_filestream *fs;
-       long sample_offset = 0;
-       long max_length;
+       int res, vres;
+       struct ast_filestream *fs, *vfs;
+       long sample_offset = 0, max_length;
+       char *edigits = "";
 
        if (argc < 4 || argc > 5)
                return RESULT_SHOWUSAGE;
+
+       if (argv[3]) 
+               edigits = argv[3];
+
        if ((argc > 4) && (sscanf(argv[4], "%ld", &sample_offset) != 1))
                return RESULT_SHOWUSAGE;
-       
-       fs = ast_openstream(chan, argv[2], chan->language);
-       if (!fs){
-               fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
+
+       if (!(fs = ast_openstream(chan, argv[2], chan->language))) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
                return RESULT_SUCCESS;
        }
+
+       if ((vfs = ast_openvstream(chan, argv[2], chan->language)))
+               ast_debug(1, "Ooh, found a video stream, too\n");
+               
+       ast_verb(3, "Playing '%s' (escape_digits=%s) (sample_offset %ld)\n", argv[2], edigits, sample_offset);
+
        ast_seekstream(fs, 0, SEEK_END);
        max_length = ast_tellstream(fs);
        ast_seekstream(fs, sample_offset, SEEK_SET);
        res = ast_applystream(chan, fs);
-       res = ast_playstream(fs);
-       if (res) {
-               fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
-               return (res >= 0) ? RESULT_SHOWUSAGE : RESULT_FAILURE;
-       }
+       if (vfs)
+               vres = ast_applystream(chan, vfs);
+       ast_playstream(fs);
+       if (vfs)
+               ast_playstream(vfs);
+       
        res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
        /* this is to check for if ast_waitstream closed the stream, we probably are at
         * the end of the stream, return that amount, else check for the amount */
@@ -558,19 +602,18 @@ static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char
                /* Stop this command, don't print a result line, as there is a new command */
                return RESULT_SUCCESS;
        }
-       fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 /* get option - really similar to the handle_streamfile, but with a timeout */
 static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-        int res;
-        struct ast_filestream *fs;
-        long sample_offset = 0;
-        long max_length;
+       int res, vres;
+       struct ast_filestream *fs, *vfs;
+       long sample_offset = 0, max_length;
        int timeout = 0;
-       char *edigits = NULL;
+       char *edigits = "";
 
        if ( argc < 4 || argc > 5 )
                return RESULT_SHOWUSAGE;
@@ -585,46 +628,46 @@ static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, char *
                timeout = chan->pbx->dtimeout * 1000; /* in msec */
        }
 
-        fs = ast_openstream(chan, argv[2], chan->language);
-        if (!fs){
-                fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
-                ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
+       if (!(fs = ast_openstream(chan, argv[2], chan->language))) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
+               ast_log(LOG_WARNING, "Unable to open %s\n", argv[2]);
                return RESULT_SUCCESS;
-        }
-       if (option_verbose > 2)
-               ast_verbose(VERBOSE_PREFIX_3 "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
-
-        ast_seekstream(fs, 0, SEEK_END);
-        max_length = ast_tellstream(fs);
-        ast_seekstream(fs, sample_offset, SEEK_SET);
-        res = ast_applystream(chan, fs);
-        res = ast_playstream(fs);
-        if (res) {
-                fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
-                if (res >= 0)
-                        return RESULT_SHOWUSAGE;
-                else
-                        return RESULT_FAILURE;
-        }
-        res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
-        /* this is to check for if ast_waitstream closed the stream, we probably are at
-         * the end of the stream, return that amount, else check for the amount */
-        sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
-        ast_stopstream(chan);
-        if (res == 1) {
-                /* Stop this command, don't print a result line, as there is a new command */
-                return RESULT_SUCCESS;
-        }
+       }
+
+       if ((vfs = ast_openvstream(chan, argv[2], chan->language)))
+               ast_debug(1, "Ooh, found a video stream, too\n");
+       
+       ast_verb(3, "Playing '%s' (escape_digits=%s) (timeout %d)\n", argv[2], edigits, timeout);
+
+       ast_seekstream(fs, 0, SEEK_END);
+       max_length = ast_tellstream(fs);
+       ast_seekstream(fs, sample_offset, SEEK_SET);
+       res = ast_applystream(chan, fs);
+       if (vfs)
+               vres = ast_applystream(chan, vfs);
+       ast_playstream(fs);
+       if (vfs)
+               ast_playstream(vfs);
+
+       res = ast_waitstream_full(chan, argv[3], agi->audio, agi->ctrl);
+       /* this is to check for if ast_waitstream closed the stream, we probably are at
+        * the end of the stream, return that amount, else check for the amount */
+       sample_offset = (chan->stream)?ast_tellstream(fs):max_length;
+       ast_stopstream(chan);
+       if (res == 1) {
+               /* Stop this command, don't print a result line, as there is a new command */
+               return RESULT_SUCCESS;
+       }
 
        /* If the user didnt press a key, wait for digitTimeout*/
        if (res == 0 ) {
                res = ast_waitfordigit_full(chan, timeout, agi->audio, agi->ctrl);
                /* Make sure the new result is in the escape digits of the GET OPTION */
                if ( !strchr(edigits,res) )
-                       res=0;
+                       res=0;
        }
 
-        fdprintf(agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d endpos=%ld\n", res, sample_offset);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
@@ -632,27 +675,25 @@ static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, char *
 
 
 /*--- handle_saynumber: Say number in various language syntaxes ---*/
-/* Need to add option for gender here as well. Coders wanted */
-/* While waiting, we're sending a (char *) NULL.  */
+/* While waiting, we're sending a NULL.  */
 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res;
-       int num;
-       if (argc != 4)
+       int res, num;
+
+       if (argc < 4 || argc > 5)
                return RESULT_SHOWUSAGE;
        if (sscanf(argv[2], "%d", &num) != 1)
                return RESULT_SHOWUSAGE;
-       res = ast_say_number_full(chan, num, argv[3], chan->language, (char *) NULL, agi->audio, agi->ctrl);
+       res = ast_say_number_full(chan, num, argv[3], chan->language, argc > 4 ? argv[4] : NULL, agi->audio, agi->ctrl);
        if (res == 1)
                return RESULT_SUCCESS;
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res;
-       int num;
+       int res, num;
 
        if (argc != 4)
                return RESULT_SHOWUSAGE;
@@ -662,7 +703,7 @@ static int handle_saydigits(struct ast_channel *chan, AGI *agi, int argc, char *
        res = ast_say_digit_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
        if (res == 1) /* New command */
                return RESULT_SUCCESS;
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
@@ -676,14 +717,14 @@ static int handle_sayalpha(struct ast_channel *chan, AGI *agi, int argc, char *a
        res = ast_say_character_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
        if (res == 1) /* New command */
                return RESULT_SUCCESS;
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res;
-       int num;
+       int res, num;
+
        if (argc != 4)
                return RESULT_SHOWUSAGE;
        if (sscanf(argv[2], "%d", &num) != 1)
@@ -691,14 +732,14 @@ static int handle_saydate(struct ast_channel *chan, AGI *agi, int argc, char *ar
        res = ast_say_date(chan, num, argv[3], chan->language);
        if (res == 1)
                return RESULT_SUCCESS;
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res;
-       int num;
+       int res, num;
+
        if (argc != 4)
                return RESULT_SHOWUSAGE;
        if (sscanf(argv[2], "%d", &num) != 1)
@@ -706,15 +747,15 @@ static int handle_saytime(struct ast_channel *chan, AGI *agi, int argc, char *ar
        res = ast_say_time(chan, num, argv[3], chan->language);
        if (res == 1)
                return RESULT_SUCCESS;
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res=0;
+       int res = 0;
        time_t unixtime;
-       char *format, *zone=NULL;
+       char *format, *zone = NULL;
        
        if (argc < 4)
                return RESULT_SHOWUSAGE;
@@ -740,7 +781,7 @@ static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, char
        if (res == 1)
                return RESULT_SUCCESS;
 
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
@@ -754,16 +795,14 @@ static int handle_sayphonetic(struct ast_channel *chan, AGI *agi, int argc, char
        res = ast_say_phonetic_str_full(chan, argv[2], argv[3], chan->language, agi->audio, agi->ctrl);
        if (res == 1) /* New command */
                return RESULT_SUCCESS;
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int res;
+       int res, max, timeout;
        char data[1024];
-       int max;
-       int timeout;
 
        if (argc < 3)
                return RESULT_SHOWUSAGE;
@@ -779,11 +818,11 @@ static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, char *ar
        if (res == 2)                   /* New command */
                return RESULT_SUCCESS;
        else if (res == 1)
-               fdprintf(agi->fd, "200 result=%s (timeout)\n", data);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%s (timeout)\n", data);
        else if (res < 0 )
-               fdprintf(agi->fd, "200 result=-1\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=-1\n");
        else
-               fdprintf(agi->fd, "200 result=%s\n", data);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%s\n", data);
        return RESULT_SUCCESS;
 }
 
@@ -793,7 +832,7 @@ static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, char
        if (argc != 3)
                return RESULT_SHOWUSAGE;
        ast_copy_string(chan->context, argv[2], sizeof(chan->context));
-       fdprintf(agi->fd, "200 result=0\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
        
@@ -802,13 +841,14 @@ static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, cha
        if (argc != 3)
                return RESULT_SHOWUSAGE;
        ast_copy_string(chan->exten, argv[2], sizeof(chan->exten));
-       fdprintf(agi->fd, "200 result=0\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
 
 static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char **argv)
 {
        int pri;
+
        if (argc != 3)
                return RESULT_SHOWUSAGE;        
 
@@ -818,7 +858,7 @@ static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char
        }
 
        ast_explicit_goto(chan, NULL, NULL, pri);
-       fdprintf(agi->fd, "200 result=0\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
                
@@ -831,13 +871,13 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
        int res = 0;
        int ms;
 
-        struct ast_dsp *sildet=NULL;         /* silence detector dsp */
-        int totalsilence = 0;
-        int dspsilence = 0;
-        int silence = 0;                /* amount of silence to allow */
-        int gotsilence = 0;             /* did we timeout for silence? */
-        char *silencestr=NULL;
-        int rfmt=0;
+       struct ast_dsp *sildet=NULL;         /* silence detector dsp */
+       int totalsilence = 0;
+       int dspsilence = 0;
+       int silence = 0;                /* amount of silence to allow */
+       int gotsilence = 0;             /* did we timeout for silence? */
+       char *silencestr=NULL;
+       int rfmt=0;
 
 
        /* XXX EAGI FIXME XXX */
@@ -860,27 +900,27 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
                                silencestr++;
                                silencestr++;
                                if (silencestr)
-                                       silence = atoi(silencestr);
-                               if (silence > 0)
-                                       silence *= 1000;
-                       }
+                                       silence = atoi(silencestr);
+                               if (silence > 0)
+                                       silence *= 1000;
+                       }
                }
        }
 
-        if (silence > 0) {
-               rfmt = chan->readformat;
-                res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
-                if (res < 0) {
-                       ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
-                        return -1;
-                }
-                       sildet = ast_dsp_new();
-                if (!sildet) {
-                       ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
-                        return -1;
-                }
-                       ast_dsp_set_threshold(sildet, 256);
-       }
+       if (silence > 0) {
+               rfmt = chan->readformat;
+               res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
+               if (res < 0) {
+                       ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
+                       return -1;
+               }
+               sildet = ast_dsp_new();
+               if (!sildet) {
+                       ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
+                       return -1;
+               }
+               ast_dsp_set_threshold(sildet, 256);
+       }
 
        /* backward compatibility, if no offset given, arg[6] would have been
         * caught below and taken to be a beep, else if it is a digit then it is a
@@ -894,17 +934,20 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
        if (!res)
                res = ast_waitstream(chan, argv[4]);
        if (res) {
-               fdprintf(agi->fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d (randomerror) endpos=%ld\n", res, sample_offset);
        } else {
-               fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, 0644);
+               fs = ast_writefile(argv[2], argv[3], NULL, O_CREAT | O_WRONLY | (sample_offset ? O_APPEND : 0), 0, AST_FILE_MODE);
                if (!fs) {
                        res = -1;
-                       fdprintf(agi->fd, "200 result=%d (writefile)\n", res);
+                       ast_agi_fdprintf(chan, agi->fd, "200 result=%d (writefile)\n", res);
                        if (sildet)
                                ast_dsp_free(sildet);
                        return RESULT_FAILURE;
                }
                
+               /* Request a video update */
+               ast_indicate(chan, AST_CONTROL_VIDUPDATE);
+       
                chan->stream = fs;
                ast_applystream(chan,fs);
                /* really should have checks */
@@ -916,14 +959,14 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
                        res = ast_waitfor(chan, -1);
                        if (res < 0) {
                                ast_closestream(fs);
-                               fdprintf(agi->fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
+                               ast_agi_fdprintf(chan, agi->fd, "200 result=%d (waitfor) endpos=%ld\n", res,sample_offset);
                                if (sildet)
                                        ast_dsp_free(sildet);
                                return RESULT_FAILURE;
                        }
                        f = ast_read(chan);
                        if (!f) {
-                               fdprintf(agi->fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
+                               ast_agi_fdprintf(chan, agi->fd, "200 result=%d (hangup) endpos=%ld\n", 0, sample_offset);
                                ast_closestream(fs);
                                if (sildet)
                                        ast_dsp_free(sildet);
@@ -938,7 +981,7 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
                                        ast_stream_rewind(fs, 200);
                                        ast_truncstream(fs);
                                        sample_offset = ast_tellstream(fs);
-                                       fdprintf(agi->fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
+                                       ast_agi_fdprintf(chan, agi->fd, "200 result=%d (dtmf) endpos=%ld\n", f->subclass, sample_offset);
                                        ast_closestream(fs);
                                        ast_frfree(f);
                                        if (sildet)
@@ -952,43 +995,47 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
                                 * is valid after a write, and it will then have our current
                                 * location */
                                sample_offset = ast_tellstream(fs);
-                                if (silence > 0) {
-                                       dspsilence = 0;
-                                        ast_dsp_silence(sildet, f, &dspsilence);
-                                        if (dspsilence) {
-                                                       totalsilence = dspsilence;
-                                        } else {
-                                               totalsilence = 0;
-                                        }
-                                        if (totalsilence > silence) {
-                                             /* Ended happily with silence */
-                                               ast_frfree(f);
-                                                gotsilence = 1;
-                                                break;
-                                        }
-                               }
+                               if (silence > 0) {
+                                       dspsilence = 0;
+                                       ast_dsp_silence(sildet, f, &dspsilence);
+                                       if (dspsilence) {
+                                               totalsilence = dspsilence;
+                                       } else {
+                                               totalsilence = 0;
+                                       }
+                                       if (totalsilence > silence) {
+                                               /* Ended happily with silence */
+                                               gotsilence = 1;
+                                               break;
+                                       }
+                               }
+                               break;
+                       case AST_FRAME_VIDEO:
+                               ast_writestream(fs, f);
+                       default:
+                               /* Ignore all other frames */
                                break;
                        }
                        ast_frfree(f);
                        if (gotsilence)
                                break;
-               }
+               }
 
-               if (gotsilence) {
-                       ast_stream_rewind(fs, silence-1000);
-                       ast_truncstream(fs);
-                       sample_offset = ast_tellstream(fs);
+                       if (gotsilence) {
+                               ast_stream_rewind(fs, silence-1000);
+                               ast_truncstream(fs);
+                               sample_offset = ast_tellstream(fs);
                }               
-               fdprintf(agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
                ast_closestream(fs);
        }
 
-        if (silence > 0) {
-                res = ast_set_read_format(chan, rfmt);
-                if (res)
-                        ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
-                ast_dsp_free(sildet);
-        }
+       if (silence > 0) {
+               res = ast_set_read_format(chan, rfmt);
+               if (res)
+                       ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
+                       ast_dsp_free(sildet);
+       }
        return RESULT_SUCCESS;
 }
 
@@ -1006,17 +1053,18 @@ static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, char
                chan->whentohangup = time(NULL) + timeout;
        else
                chan->whentohangup = 0;
-       fdprintf(agi->fd, "200 result=0\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
 
 static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **argv)
 {
        struct ast_channel *c;
+
        if (argc == 1) {
                /* no argument: hangup the current channel */
                ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
-               fdprintf(agi->fd, "200 result=1\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
                return RESULT_SUCCESS;
        } else if (argc == 2) {
                /* one argument: look for info on the specified channel */
@@ -1024,12 +1072,12 @@ static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **ar
                if (c) {
                        /* we have a matching channel */
                        ast_softhangup(c,AST_SOFTHANGUP_EXPLICIT);
-                       fdprintf(agi->fd, "200 result=1\n");
+                       ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
                        ast_channel_unlock(c);
                        return RESULT_SUCCESS;
                }
                /* if we get this far no channel name matched the argument given */
-               fdprintf(agi->fd, "200 result=-1\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=-1\n");
                return RESULT_SUCCESS;
        } else {
                return RESULT_SHOWUSAGE;
@@ -1044,19 +1092,17 @@ static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, char **argv
        if (argc < 2)
                return RESULT_SHOWUSAGE;
 
-       if (option_verbose > 2)
-               ast_verbose(VERBOSE_PREFIX_3 "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
+       ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
 
-       app = pbx_findapp(argv[1]);
-
-       if (app) {
+       if ((app = pbx_findapp(argv[1]))) {
                res = pbx_exec(chan, app, argv[2]);
        } else {
                ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
                res = -2;
        }
-       fdprintf(agi->fd, "200 result=%d\n", res);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
 
+       /* Even though this is wrong, users are depending upon this result. */
        return res;
 }
 
@@ -1077,7 +1123,7 @@ static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, char
                ast_set_callerid(chan, l, n, NULL);
        }
 
-       fdprintf(agi->fd, "200 result=1\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
        return RESULT_SUCCESS;
 }
 
@@ -1086,18 +1132,18 @@ static int handle_channelstatus(struct ast_channel *chan, AGI *agi, int argc, ch
        struct ast_channel *c;
        if (argc == 2) {
                /* no argument: supply info on the current channel */
-               fdprintf(agi->fd, "200 result=%d\n", chan->_state);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", chan->_state);
                return RESULT_SUCCESS;
        } else if (argc == 3) {
                /* one argument: look for info on the specified channel */
                c = ast_get_channel_by_name_locked(argv[2]);
                if (c) {
-                       fdprintf(agi->fd, "200 result=%d\n", c->_state);
+                       ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", c->_state);
                        ast_channel_unlock(c);
                        return RESULT_SUCCESS;
                }
                /* if we get this far no channel name matched the argument given */
-               fdprintf(agi->fd, "200 result=-1\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=-1\n");
                return RESULT_SUCCESS;
        } else {
                return RESULT_SHOWUSAGE;
@@ -1109,7 +1155,7 @@ static int handle_setvariable(struct ast_channel *chan, AGI *agi, int argc, char
        if (argv[3])
                pbx_builtin_setvar_helper(chan, argv[2], argv[3]);
 
-       fdprintf(agi->fd, "200 result=1\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
        return RESULT_SUCCESS;
 }
 
@@ -1129,16 +1175,16 @@ static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, char
        }
 
        if (ret)
-               fdprintf(agi->fd, "200 result=1 (%s)\n", ret);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s)\n", ret);
        else
-               fdprintf(agi->fd, "200 result=0\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
 
        return RESULT_SUCCESS;
 }
 
 static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc, char **argv)
 {
-       char tmp[4096] = "";
+       char tmp[4096];
        struct ast_channel *chan2=NULL;
 
        if ((argc != 4) && (argc != 5))
@@ -1148,11 +1194,11 @@ static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc,
        } else {
                chan2 = chan;
        }
-       if (chan) { /* XXX isn't this chan2 ? */
+       if (chan2) {
                pbx_substitute_variables_helper(chan2, argv[3], tmp, sizeof(tmp) - 1);
-               fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s)\n", tmp);
        } else {
-               fdprintf(agi->fd, "200 result=0\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        }
        if (chan2 && (chan2 != chan))
                ast_channel_unlock(chan2);
@@ -1189,7 +1235,7 @@ static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **a
        if (level <= option_verbose)
                ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
        
-       fdprintf(agi->fd, "200 result=1\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
        
        return RESULT_SUCCESS;
 }
@@ -1203,9 +1249,9 @@ static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, char **arg
                return RESULT_SHOWUSAGE;
        res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
        if (res) 
-               fdprintf(agi->fd, "200 result=0\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        else
-               fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s)\n", tmp);
 
        return RESULT_SUCCESS;
 }
@@ -1217,7 +1263,7 @@ static int handle_dbput(struct ast_channel *chan, AGI *agi, int argc, char **arg
        if (argc != 5)
                return RESULT_SHOWUSAGE;
        res = ast_db_put(argv[2], argv[3], argv[4]);
-       fdprintf(agi->fd, "200 result=%c\n", res ? '0' : '1');
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%c\n", res ? '0' : '1');
        return RESULT_SUCCESS;
 }
 
@@ -1228,13 +1274,14 @@ static int handle_dbdel(struct ast_channel *chan, AGI *agi, int argc, char **arg
        if (argc != 4)
                return RESULT_SHOWUSAGE;
        res = ast_db_del(argv[2], argv[3]);
-       fdprintf(agi->fd, "200 result=%c\n", res ? '0' : '1');
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%c\n", res ? '0' : '1');
        return RESULT_SUCCESS;
 }
 
 static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char **argv)
 {
        int res;
+
        if ((argc < 3) || (argc > 4))
                return RESULT_SHOWUSAGE;
        if (argc == 4)
@@ -1242,55 +1289,52 @@ static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char *
        else
                res = ast_db_deltree(argv[2], NULL);
 
-       fdprintf(agi->fd, "200 result=%c\n", res ? '0' : '1');
-       return RESULT_SUCCESS;
-}
-
-static char debug_usage[] = 
-"Usage: agi debug\n"
-"       Enables dumping of AGI transactions for debugging purposes\n";
-
-static char no_debug_usage[] = 
-"Usage: agi no debug\n"
-"       Disables dumping of AGI transactions for debugging purposes\n";
-
-static int agi_do_debug(int fd, int argc, char *argv[])
-{
-       if (argc != 2)
-               return RESULT_SHOWUSAGE;
-       agidebug = 1;
-       ast_cli(fd, "AGI Debugging Enabled\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%c\n", res ? '0' : '1');
        return RESULT_SUCCESS;
 }
 
-static int agi_no_debug(int fd, int argc, char *argv[])
+static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       if (argc != 3)
-               return RESULT_SHOWUSAGE;
-       agidebug = 0;
-       ast_cli(fd, "AGI Debugging Disabled\n");
-       return RESULT_SUCCESS;
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "agi debug [off]";
+               e->usage =
+                       "Usage: agi debug [off]\n"
+                       "       Enables/disables dumping of AGI transactions for\n"
+                       "       debugging purposes.\n";
+               return NULL;
+
+       case CLI_GENERATE:
+               return NULL;
+       }
+       if (a->argc < e->args - 1 || a->argc > e->args )
+               return CLI_SHOWUSAGE;
+       if (a->argc == e->args - 1) {
+               agidebug = 1;
+       } else {
+               if (strncasecmp(a->argv[e->args - 1], "off", 3) == 0) {
+                       agidebug = 0;
+               } else {
+                       return CLI_SHOWUSAGE;
+               }
+       }
+       ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
+       return CLI_SUCCESS;
 }
 
-static struct ast_cli_entry  cli_debug =
-       { { "agi", "debug", NULL }, agi_do_debug, "Enable AGI debugging", debug_usage };
-
-static struct ast_cli_entry  cli_no_debug =
-       { { "agi", "no", "debug", NULL }, agi_no_debug, "Disable AGI debugging", no_debug_usage };
-
 static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
 {
-       fdprintf(agi->fd, "200 result=0\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
 
 static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
        if (!strncasecmp(argv[2], "on", 2))
-               ast_moh_start(chan, argc > 3 ? argv[3] : NULL);
+               ast_moh_start(chan, argc > 3 ? argv[3] : NULL, NULL);
        else if (!strncasecmp(argv[2], "off", 3))
                ast_moh_stop(chan);
-       fdprintf(agi->fd, "200 result=0\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
 
@@ -1447,7 +1491,7 @@ static char usage_getoption[] =
 "      Behaves similar to STREAM FILE but used with a timeout option.\n";
 
 static char usage_saynumber[] =
-" Usage: SAY NUMBER <number> <escape digits>\n"
+" Usage: SAY NUMBER <number> <escape digits> [gender]\n"
 "      Say a given number, returning early if any of the given DTMF digits\n"
 " are received on the channel.  Returns 0 if playback completes without a digit\n"
 " being pressed, or the ASCII numerical value of the digit if one was pressed or\n"
@@ -1541,56 +1585,62 @@ static char usage_noop[] =
 " Usage: NoOp\n"
 "      Does nothing.\n";
 
-static agi_command commands[MAX_COMMANDS] = {
-       { { "answer", NULL }, handle_answer, "Answer channel", usage_answer },
-       { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus },
-       { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel },
-       { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree },
-       { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget },
-       { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput },
-       { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec },
-       { { "get", "data", NULL }, handle_getdata, "Prompts for DTMF on a channel", usage_getdata },
-       { { "get", "full", "variable", NULL }, handle_getvariablefull, "Evaluates a channel expression", usage_getvariablefull },
-       { { "get", "option", NULL }, handle_getoption, "Stream file, prompt for DTMF, with timeout", usage_getoption },
-       { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable },
-       { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup },
-       { { "noop", NULL }, handle_noop, "Does nothing", usage_noop },
-       { { "receive", "char", NULL }, handle_recvchar, "Receives one character from channels supporting it", usage_recvchar },
-       { { "receive", "text", NULL }, handle_recvtext, "Receives text from channels supporting it", usage_recvtext },
-       { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile },
-       { { "say", "alpha", NULL }, handle_sayalpha, "Says a given character string", usage_sayalpha },
-       { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits },
-       { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber },
-       { { "say", "phonetic", NULL }, handle_sayphonetic, "Says a given character string with phonetics", usage_sayphonetic },
-       { { "say", "date", NULL }, handle_saydate, "Says a given date", usage_saydate },
-       { { "say", "time", NULL }, handle_saytime, "Says a given time", usage_saytime },
-       { { "say", "datetime", NULL }, handle_saydatetime, "Says a given time as specfied by the format given", usage_saydatetime },
-       { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage },
-       { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext },
-       { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup },
-       { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid },
-       { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext },
-       { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension },
-       { { "set", "music", NULL }, handle_setmusic, "Enable/Disable Music on hold generator", usage_setmusic },
-       { { "set", "priority", NULL }, handle_setpriority, "Set channel dialplan priority", usage_setpriority },
-       { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable },
-       { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile },
-       { { "control", "stream", "file", NULL }, handle_controlstreamfile, "Sends audio file on channel and allows the listner to control the stream", usage_controlstreamfile },
-       { { "tdd", "mode", NULL }, handle_tddmode, "Toggles TDD mode (for the deaf)", usage_tddmode },
-       { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose },
-       { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit },
+/*!
+ * \brief AGI commands list
+ */
+static struct agi_command commands[] = {
+       { { "answer", NULL }, handle_answer, "Answer channel", usage_answer , 0 },
+       { { "channel", "status", NULL }, handle_channelstatus, "Returns status of the connected channel", usage_channelstatus , 0 },
+       { { "database", "del", NULL }, handle_dbdel, "Removes database key/value", usage_dbdel , 1 },
+       { { "database", "deltree", NULL }, handle_dbdeltree, "Removes database keytree/value", usage_dbdeltree , 1 },
+       { { "database", "get", NULL }, handle_dbget, "Gets database value", usage_dbget , 1 },
+       { { "database", "put", NULL }, handle_dbput, "Adds/updates database value", usage_dbput , 1 },
+       { { "exec", NULL }, handle_exec, "Executes a given Application", usage_exec , 1 },
+       { { "get", "data", NULL }, handle_getdata, "Prompts for DTMF on a channel", usage_getdata , 0 },
+       { { "get", "full", "variable", NULL }, handle_getvariablefull, "Evaluates a channel expression", usage_getvariablefull , 1 },
+       { { "get", "option", NULL }, handle_getoption, "Stream file, prompt for DTMF, with timeout", usage_getoption , 0 },
+       { { "get", "variable", NULL }, handle_getvariable, "Gets a channel variable", usage_getvariable , 1 },
+       { { "hangup", NULL }, handle_hangup, "Hangup the current channel", usage_hangup , 0 },
+       { { "noop", NULL }, handle_noop, "Does nothing", usage_noop , 1 },
+       { { "receive", "char", NULL }, handle_recvchar, "Receives one character from channels supporting it", usage_recvchar , 0 },
+       { { "receive", "text", NULL }, handle_recvtext, "Receives text from channels supporting it", usage_recvtext , 0 },
+       { { "record", "file", NULL }, handle_recordfile, "Records to a given file", usage_recordfile , 0 },
+       { { "say", "alpha", NULL }, handle_sayalpha, "Says a given character string", usage_sayalpha , 0 },
+       { { "say", "digits", NULL }, handle_saydigits, "Says a given digit string", usage_saydigits , 0 },
+       { { "say", "number", NULL }, handle_saynumber, "Says a given number", usage_saynumber , 0 },
+       { { "say", "phonetic", NULL }, handle_sayphonetic, "Says a given character string with phonetics", usage_sayphonetic , 0 },
+       { { "say", "date", NULL }, handle_saydate, "Says a given date", usage_saydate , 0 },
+       { { "say", "time", NULL }, handle_saytime, "Says a given time", usage_saytime , 0 },
+       { { "say", "datetime", NULL }, handle_saydatetime, "Says a given time as specfied by the format given", usage_saydatetime , 0 },
+       { { "send", "image", NULL }, handle_sendimage, "Sends images to channels supporting it", usage_sendimage , 0 },
+       { { "send", "text", NULL }, handle_sendtext, "Sends text to channels supporting it", usage_sendtext , 0 },
+       { { "set", "autohangup", NULL }, handle_autohangup, "Autohangup channel in some time", usage_autohangup , 0 },
+       { { "set", "callerid", NULL }, handle_setcallerid, "Sets callerid for the current channel", usage_setcallerid , 0 },
+       { { "set", "context", NULL }, handle_setcontext, "Sets channel context", usage_setcontext , 0 },
+       { { "set", "extension", NULL }, handle_setextension, "Changes channel extension", usage_setextension , 0 },
+       { { "set", "music", NULL }, handle_setmusic, "Enable/Disable Music on hold generator", usage_setmusic , 0 },
+       { { "set", "priority", NULL }, handle_setpriority, "Set channel dialplan priority", usage_setpriority , 0 },
+       { { "set", "variable", NULL }, handle_setvariable, "Sets a channel variable", usage_setvariable , 1 },
+       { { "stream", "file", NULL }, handle_streamfile, "Sends audio file on channel", usage_streamfile , 0 },
+       { { "control", "stream", "file", NULL }, handle_controlstreamfile, "Sends audio file on channel and allows the listner to control the stream", usage_controlstreamfile , 0 },
+       { { "tdd", "mode", NULL }, handle_tddmode, "Toggles TDD mode (for the deaf)", usage_tddmode , 0 },
+       { { "verbose", NULL }, handle_verbose, "Logs a message to the asterisk verbose log", usage_verbose , 1 },
+       { { "wait", "for", "digit", NULL }, handle_waitfordigit, "Waits for a digit to be pressed", usage_waitfordigit , 0 },
 };
 
-static int help_workhorse(int fd, char *match[])
+static AST_RWLIST_HEAD_STATIC(agi_commands, agi_command);
+
+static char *help_workhorse(int fd, char *match[])
 {
-       char fullcmd[80];
-       char matchstr[80];
-       int x;
+       char fullcmd[80], matchstr[80];
        struct agi_command *e;
+
        if (match)
                ast_join(matchstr, sizeof(matchstr), match);
-       for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
-               e = &commands[x]; 
+
+       ast_cli(fd, "%5.5s %20.20s   %s\n","Dead","Command","Description");
+       AST_RWLIST_RDLOCK(&agi_commands);
+       AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
                if (!e->cmda[0])
                        break;
                /* Hide commands that start with '_' */
@@ -1599,80 +1649,115 @@ static int help_workhorse(int fd, char *match[])
                ast_join(fullcmd, sizeof(fullcmd), e->cmda);
                if (match && strncasecmp(matchstr, fullcmd, strlen(matchstr)))
                        continue;
-               ast_cli(fd, "%20.20s   %s\n", fullcmd, e->summary);
+               ast_cli(fd, "%5.5s %20.20s   %s\n", e->dead ? "Yes" : "No" , fullcmd, e->summary);
        }
-       return 0;
+       AST_RWLIST_UNLOCK(&agi_commands);
+
+       return CLI_SUCCESS;
 }
 
-int agi_register(agi_command *agi)
+int ast_agi_register(struct ast_module *mod, agi_command *cmd)
 {
-       int x;
-       for (x=0; x<MAX_COMMANDS - 1; x++) {
-               if (commands[x].cmda[0] == agi->cmda[0]) {
-                       ast_log(LOG_WARNING, "Command already registered!\n");
-                       return -1;
-               }
-       }
-       for (x=0; x<MAX_COMMANDS - 1; x++) {
-               if (!commands[x].cmda[0]) {
-                       commands[x] = *agi;
-                       return 0;
-               }
+       char fullcmd[80];
+
+       ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
+
+       if (!find_command(cmd->cmda,1)) {
+               cmd->mod = mod;
+               AST_RWLIST_WRLOCK(&agi_commands);
+               AST_LIST_INSERT_TAIL(&agi_commands, cmd, list);
+               AST_RWLIST_UNLOCK(&agi_commands);
+               if (mod != ast_module_info->self)
+                       ast_module_ref(ast_module_info->self);
+               ast_verb(2, "AGI Command '%s' registered\n",fullcmd);
+               return 1;
+       } else {
+               ast_log(LOG_WARNING, "Command already registered!\n");
+               return 0;
        }
-       ast_log(LOG_WARNING, "No more room for new commands!\n");
-       return -1;
 }
 
-void agi_unregister(agi_command *agi)
+int ast_agi_unregister(struct ast_module *mod, agi_command *cmd)
 {
-       int x;
-       for (x=0; x<MAX_COMMANDS - 1; x++) {
-               if (commands[x].cmda[0] == agi->cmda[0]) {
-                       memset(&commands[x], 0, sizeof(agi_command));
+       struct agi_command *e;
+       int unregistered = 0;
+       char fullcmd[80];
+       
+       ast_join(fullcmd, sizeof(fullcmd), cmd->cmda);
+
+       AST_RWLIST_WRLOCK(&agi_commands);
+       AST_RWLIST_TRAVERSE_SAFE_BEGIN(&agi_commands, e, list) {
+               if (cmd == e) {
+                       AST_RWLIST_REMOVE_CURRENT(list);
+                       if (mod != ast_module_info->self)
+                               ast_module_unref(ast_module_info->self);
+                       unregistered=1;
+                       break;
                }
        }
+       AST_RWLIST_TRAVERSE_SAFE_END;
+       AST_RWLIST_UNLOCK(&agi_commands);
+       if (unregistered)
+               ast_verb(2, "AGI Command '%s' unregistered\n",fullcmd);
+       else
+               ast_log(LOG_WARNING, "Unable to unregister command: '%s'!\n",fullcmd);
+       return unregistered;
+}
+
+void ast_agi_register_multiple(struct ast_module *mod, agi_command *cmd, int len)
+{
+       int i;
+
+       for (i = 0; i < len; i++)
+               ast_agi_register(mod, cmd + i);
+
+}
+
+void ast_agi_unregister_multiple(struct ast_module *mod, agi_command *cmd, int len)
+{
+       int i;
+
+       for (i = 0; i < len; i++)
+               ast_agi_unregister(mod, cmd + i);
 }
 
 static agi_command *find_command(char *cmds[], int exact)
 {
-       int x;
-       int y;
-       int match;
+       int y, match;
+       struct agi_command *e;
 
-       for (x=0; x < sizeof(commands) / sizeof(commands[0]); x++) {
-               if (!commands[x].cmda[0])
+       AST_RWLIST_RDLOCK(&agi_commands);
+       AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
+               if (!e->cmda[0])
                        break;
                /* start optimistic */
                match = 1;
-               for (y=0; match && cmds[y]; y++) {
+               for (y = 0; match && cmds[y]; y++) {
                        /* If there are no more words in the command (and we're looking for
                           an exact match) or there is a difference between the two words,
                           then this is not a match */
-                       if (!commands[x].cmda[y] && !exact)
+                       if (!e->cmda[y] && !exact)
                                break;
                        /* don't segfault if the next part of a command doesn't exist */
-                       if (!commands[x].cmda[y])
+                       if (!e->cmda[y])
                                return NULL;
-                       if (strcasecmp(commands[x].cmda[y], cmds[y]))
+                       if (strcasecmp(e->cmda[y], cmds[y]))
                                match = 0;
                }
                /* If more words are needed to complete the command then this is not
                   a candidate (unless we're looking for a really inexact answer  */
-               if ((exact > -1) && commands[x].cmda[y])
+               if ((exact > -1) && e->cmda[y])
                        match = 0;
                if (match)
-                       return &commands[x];
+                       return e;
        }
+       AST_RWLIST_UNLOCK(&agi_commands);
        return NULL;
 }
 
-
 static int parse_args(char *s, int *max, char *argv[])
 {
-       int x=0;
-       int quoted=0;
-       int escaped=0;
-       int whitespace=1;
+       int x = 0, quoted = 0, escaped = 0, whitespace = 1;
        char *cur;
 
        cur = s;
@@ -1733,27 +1818,26 @@ normal:
        return 0;
 }
 
-static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf)
+static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead)
 {
        char *argv[MAX_ARGS];
-       int argc = MAX_ARGS;
-       int res;
+       int argc = MAX_ARGS, res;
        agi_command *c;
 
        parse_args(buf, &argc, argv);
-#if    0
-       { int x;
-       for (x=0; x<argc; x++) 
-               fprintf(stderr, "Got Arg%d: %s\n", x, argv[x]); }
-#endif
-       c = find_command(argv, 0);
-       if (c) {
+       if ((c = find_command(argv, 0)) && (!dead || (dead && c->dead))) {
+               /* if this command wasnt registered by res_agi, be sure to usecount
+               the module we are using */
+               if (c->mod != ast_module_info->self)
+                       ast_module_ref(c->mod);
                res = c->handler(chan, agi, argc, argv);
+               if (c->mod != ast_module_info->self)
+                       ast_module_unref(c->mod);
                switch(res) {
                case RESULT_SHOWUSAGE:
-                       fdprintf(agi->fd, "520-Invalid command syntax.  Proper usage follows:\n");
-                       fdprintf(agi->fd, c->usage);
-                       fdprintf(agi->fd, "520 End of proper usage.\n");
+                       ast_agi_fdprintf(chan, agi->fd, "520-Invalid command syntax.  Proper usage follows:\n");
+                       ast_agi_fdprintf(chan, agi->fd, c->usage);
+                       ast_agi_fdprintf(chan, agi->fd, "520 End of proper usage.\n");
                        break;
                case AST_PBX_KEEPALIVE:
                        /* We've been asked to keep alive, so do so */
@@ -1764,45 +1848,52 @@ static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf)
                           appropriately */
                        return -1;
                }
+       } else if ((c = find_command(argv, 0))) {
+               ast_agi_fdprintf(chan, agi->fd, "511 Command Not Permitted on a dead channel\n");
        } else {
-               fdprintf(agi->fd, "510 Invalid or unknown command\n");
+               ast_agi_fdprintf(chan, agi->fd, "510 Invalid or unknown command\n");
        }
        return 0;
 }
-#define RETRY  3
-static int run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid, int dead)
+static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid, int *status, int dead, int argc, char *argv[])
 {
        struct ast_channel *c;
-       int outfd;
-       int ms;
-       int returnstatus = 0;
+       int outfd, ms, needhup = 0;
+       enum agi_result returnstatus = AGI_RESULT_SUCCESS;
        struct ast_frame *f;
-       char buf[2048];
+       char buf[AGI_BUF_LEN];
+       char *res = NULL;
        FILE *readf;
        /* how many times we'll retry if ast_waitfor_nandfs will return without either 
          channel or file descriptor in case select is interrupted by a system call (EINTR) */
-       int retry = RETRY;
+       int retry = AGI_NANDFS_RETRY;
 
        if (!(readf = fdopen(agi->ctrl, "r"))) {
                ast_log(LOG_WARNING, "Unable to fdopen file descriptor\n");
                if (pid > -1)
                        kill(pid, SIGHUP);
                close(agi->ctrl);
-               return -1;
+               return AGI_RESULT_FAILURE;
        }
        setlinebuf(readf);
-       setup_env(chan, request, agi->fd, (agi->audio > -1));
+       setup_env(chan, request, agi->fd, (agi->audio > -1), argc, argv);
        for (;;) {
+               if (needhup) {
+                       needhup = 0;
+                       dead = 1;
+                       kill(pid, SIGHUP);
+               }
                ms = -1;
                c = ast_waitfor_nandfds(&chan, dead ? 0 : 1, &agi->ctrl, 1, NULL, &outfd, &ms);
                if (c) {
-                       retry = RETRY;
+                       retry = AGI_NANDFS_RETRY;
                        /* Idle the channel until we get a command */
                        f = ast_read(c);
                        if (!f) {
-                               ast_log(LOG_DEBUG, "%s hungup\n", chan->name);
-                               returnstatus = -1;
-                               break;
+                               ast_debug(1, "%s hungup\n", chan->name);
+                               returnstatus = AGI_RESULT_HANGUP;
+                               needhup = 1;
+                               continue;
                        } else {
                                /* If it's voice, write it to the audio pipe */
                                if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
@@ -1812,185 +1903,291 @@ static int run_agi(struct ast_channel *chan, char *request, AGI *agi, int pid, i
                                ast_frfree(f);
                        }
                } else if (outfd > -1) {
-                       retry = RETRY;
-                       if (!fgets(buf, sizeof(buf), readf)) {
+                       size_t len = sizeof(buf);
+                       size_t buflen = 0;
+
+                       retry = AGI_NANDFS_RETRY;
+                       buf[0] = '\0';
+
+                       while (buflen < (len - 1)) {
+                               res = fgets(buf + buflen, len, readf);
+                               if (feof(readf)) 
+                                       break;
+                               if (ferror(readf) && ((errno != EINTR) && (errno != EAGAIN))) 
+                                       break;
+                               if (res != NULL && !agi->fast)
+                                       break;
+                               buflen = strlen(buf);
+                               if (buflen && buf[buflen - 1] == '\n')
+                                       break;
+                               len -= buflen;
+                               if (agidebug)
+                                       ast_verbose( "AGI Rx << temp buffer %s - errno %s\n", buf, strerror(errno));
+                       }
+
+                       if (!buf[0]) {
                                /* Program terminated */
-                               if (returnstatus)
+                               if (returnstatus && returnstatus != AST_PBX_KEEPALIVE)
                                        returnstatus = -1;
-                               if (option_verbose > 2) 
-                                       ast_verbose(VERBOSE_PREFIX_3 "AGI Script %s completed, returning %d\n", request, returnstatus);
+                               ast_verb(3, "<%s>AGI Script %s completed, returning %d\n", chan->name, request, returnstatus);
+                               if (pid > 0)
+                                       waitpid(pid, status, 0);
                                /* No need to kill the pid anymore, since they closed us */
                                pid = -1;
                                break;
                        }
+
                        /* get rid of trailing newline, if any */
                        if (*buf && buf[strlen(buf) - 1] == '\n')
                                buf[strlen(buf) - 1] = 0;
                        if (agidebug)
-                               ast_verbose("AGI Rx << %s\n", buf);
-                       returnstatus |= agi_handle_command(chan, agi, buf);
+                               ast_verbose("<%s>AGI Rx << %s\n", chan->name, buf);
+                       returnstatus |= agi_handle_command(chan, agi, buf, dead);
                        /* If the handle_command returns -1, we need to stop */
                        if ((returnstatus < 0) || (returnstatus == AST_PBX_KEEPALIVE)) {
-                               break;
+                               needhup = 1;
+                               continue;
                        }
                } else {
                        if (--retry <= 0) {
                                ast_log(LOG_WARNING, "No channel, no fd?\n");
-                               returnstatus = -1;
+                               returnstatus = AGI_RESULT_FAILURE;
                                break;
                        }
                }
        }
        /* Notify process */
        if (pid > -1) {
-               if (kill(pid, SIGHUP))
-                       ast_log(LOG_WARNING, "unable to send SIGHUP to AGI process %d: %s\n", pid, strerror(errno));
+               const char *sighup = pbx_builtin_getvar_helper(chan, "AGISIGHUP");
+               if (ast_strlen_zero(sighup) || !ast_false(sighup)) {
+                       if (kill(pid, SIGHUP))
+                               ast_log(LOG_WARNING, "unable to send SIGHUP to AGI process %d: %s\n", pid, strerror(errno));
+               }
        }
        fclose(readf);
        return returnstatus;
 }
 
-static int handle_showagi(int fd, int argc, char *argv[])
+static char *handle_cli_agi_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       struct agi_command *e;
+       struct agi_command *command;
        char fullcmd[80];
-       if ((argc < 2))
-               return RESULT_SHOWUSAGE;
-       if (argc > 2) {
-               e = find_command(argv + 2, 1);
-               if (e) 
-                       ast_cli(fd, e->usage);
-               else {
-                       if (find_command(argv + 2, -1)) {
-                               return help_workhorse(fd, argv + 1);
+
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "agi show";
+               e->usage =
+                       "Usage: agi show [topic]\n"
+                       "       When called with a topic as an argument, displays usage\n"
+                       "       information on the given command.  If called without a\n"
+                       "       topic, it provides a list of AGI commands.\n";
+               break;
+       case CLI_GENERATE:
+               return NULL;
+       }
+       if (a->argc < e->args)
+               return CLI_SHOWUSAGE;
+       if (a->argc > e->args) {
+               command = find_command(a->argv + e->args, 1);
+               if (command) {
+                       ast_cli(a->fd, command->usage);
+                       ast_cli(a->fd, " Runs Dead : %s\n", command->dead ? "Yes" : "No");
+               } else {
+                       if (find_command(a->argv + e->args, -1)) {
+                               return help_workhorse(a->fd, a->argv + e->args);
                        } else {
-                               ast_join(fullcmd, sizeof(fullcmd), argv+1);
-                               ast_cli(fd, "No such command '%s'.\n", fullcmd);
+                               ast_join(fullcmd, sizeof(fullcmd), a->argv + e->args);
+                               ast_cli(a->fd, "No such command '%s'.\n", fullcmd);
                        }
                }
        } else {
-               return help_workhorse(fd, NULL);
+               return help_workhorse(a->fd, NULL);
        }
-       return RESULT_SUCCESS;
+       return CLI_SUCCESS;
 }
 
-static int handle_dumpagihtml(int fd, int argc, char *argv[])
+/*! \brief Convert string to use HTML escaped characters
+       \note Maybe this should be a generic function?
+*/
+static void write_html_escaped(FILE *htmlfile, char *str)
 {
-       struct agi_command *e;
+       char *cur = str;
+
+       while(*cur) {
+               switch (*cur) {
+               case '<':
+                       fprintf(htmlfile, "%s", "&lt;");
+                       break;
+               case '>':
+                       fprintf(htmlfile, "%s", "&gt;");
+                       break;
+               case '&':
+                       fprintf(htmlfile, "%s", "&amp;");
+                       break;
+               case '"':
+                       fprintf(htmlfile, "%s", "&quot;");
+                       break;
+               default:
+                       fprintf(htmlfile, "%c", *cur);
+                       break;
+               }
+               cur++;
+       }
+
+       return;
+}
+
+static char *handle_cli_agi_dumphtml(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       struct agi_command *command;
        char fullcmd[80];
-       int x;
        FILE *htmlfile;
 
-       if ((argc < 3))
-               return RESULT_SHOWUSAGE;
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "agi dumphtml";
+               e->usage =
+                       "Usage: agi dumphtml <filename>\n"
+                       "       Dumps the AGI command list in HTML format to the given\n"
+                       "       file.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
+       if (a->argc < e->args + 1)
+               return CLI_SHOWUSAGE;
 
-       if (!(htmlfile = fopen(argv[2], "wt"))) {
-               ast_cli(fd, "Could not create file '%s'\n", argv[2]);
-               return RESULT_SHOWUSAGE;
+       if (!(htmlfile = fopen(a->argv[2], "wt"))) {
+               ast_cli(a->fd, "Could not create file '%s'\n", a->argv[2]);
+               return CLI_SHOWUSAGE;
        }
 
        fprintf(htmlfile, "<HTML>\n<HEAD>\n<TITLE>AGI Commands</TITLE>\n</HEAD>\n");
        fprintf(htmlfile, "<BODY>\n<CENTER><B><H1>AGI Commands</H1></B></CENTER>\n\n");
-
-
        fprintf(htmlfile, "<TABLE BORDER=\"0\" CELLSPACING=\"10\">\n");
 
-       for (x=0;x<sizeof(commands)/sizeof(commands[0]);x++) {
+       AST_RWLIST_RDLOCK(&agi_commands);
+       AST_RWLIST_TRAVERSE(&agi_commands, command, list) {
                char *stringp, *tempstr;
-
-               e = &commands[x]; 
-               if (!e->cmda[0])        /* end ? */
+               if (!command->cmda[0])  /* end ? */
                        break;
                /* Hide commands that start with '_' */
-               if ((e->cmda[0])[0] == '_')
+               if ((command->cmda[0])[0] == '_')
                        continue;
-               ast_join(fullcmd, sizeof(fullcmd), e->cmda);
+               ast_join(fullcmd, sizeof(fullcmd), command->cmda);
 
                fprintf(htmlfile, "<TR><TD><TABLE BORDER=\"1\" CELLPADDING=\"5\" WIDTH=\"100%%\">\n");
-               fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TD></TR>\n", fullcmd,e->summary);
+               fprintf(htmlfile, "<TR><TH ALIGN=\"CENTER\"><B>%s - %s</B></TH></TR>\n", fullcmd, command->summary);
 
-               stringp=e->usage;
+               stringp = command->usage;
                tempstr = strsep(&stringp, "\n");
 
-               fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">%s</TD></TR>\n", tempstr);
-               
+               fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">");
+               write_html_escaped(htmlfile, tempstr);
+               fprintf(htmlfile, "</TD></TR>\n");
                fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
-               while ((tempstr = strsep(&stringp, "\n")) != NULL)
-                       fprintf(htmlfile, "%s<BR>\n",tempstr);
+
+               while ((tempstr = strsep(&stringp, "\n")) != NULL) {
+                       write_html_escaped(htmlfile, tempstr);
+                       fprintf(htmlfile, "<BR>\n");
+               }
                fprintf(htmlfile, "</TD></TR>\n");
                fprintf(htmlfile, "</TABLE></TD></TR>\n\n");
-
        }
-
+       AST_RWLIST_UNLOCK(&agi_commands);
        fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
        fclose(htmlfile);
-       ast_cli(fd, "AGI HTML Commands Dumped to: %s\n", argv[2]);
-       return RESULT_SUCCESS;
+       ast_cli(a->fd, "AGI HTML commands dumped to: %s\n", a->argv[2]);
+       return CLI_SUCCESS;
 }
 
 static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced, int dead)
 {
-       int res=0;
-       struct localuser *u;
-       char *argv[MAX_ARGS];
-       char buf[2048]="";
-       char *tmp = (char *)buf;
-       int argc = 0;
-       int fds[2];
-       int efd = -1;
-       int pid;
-        char *stringp;
+       enum agi_result res;
+       struct ast_module_user *u;
+       char buf[AGI_BUF_LEN] = "", *tmp = buf;
+       int fds[2], efd = -1, pid;
+       AST_DECLARE_APP_ARGS(args,
+               AST_APP_ARG(arg)[MAX_ARGS];
+       );
        AGI agi;
 
        if (ast_strlen_zero(data)) {
                ast_log(LOG_WARNING, "AGI requires an argument (script)\n");
                return -1;
        }
+       if (dead)
+               ast_log(LOG_NOTICE, "Hungup channel detected, running agi in dead mode.");
        ast_copy_string(buf, data, sizeof(buf));
-
        memset(&agi, 0, sizeof(agi));
-        while ((stringp = strsep(&tmp, "|")) && argc < MAX_ARGS-1)
-               argv[argc++] = stringp;
-       argv[argc] = NULL;
+       AST_STANDARD_APP_ARGS(args, tmp);
+       args.argv[args.argc] = NULL;
 
-       u = ast_localuser_add(me, chan);
+       u = ast_module_user_add(chan);
 #if 0
         /* Answer if need be */
-        if (chan->_state != AST_STATE_UP) {
+       if (chan->_state != AST_STATE_UP) {
                if (ast_answer(chan)) {
                        LOCAL_USER_REMOVE(u);
                        return -1;
                }
        }
 #endif
-       res = launch_script(argv[0], argv, fds, enhanced ? &efd : NULL, &pid);
-       if (!res) {
+       res = launch_script(args.argv[0], args.argv, fds, enhanced ? &efd : NULL, &pid);
+       if (res == AGI_RESULT_SUCCESS || res == AGI_RESULT_SUCCESS_FAST) {
+               int status = 0;
                agi.fd = fds[1];
                agi.ctrl = fds[0];
                agi.audio = efd;
-               res = run_agi(chan, argv[0], &agi, pid, dead);
-               close(fds[1]);
+               agi.fast = (res == AGI_RESULT_SUCCESS_FAST) ? 1 : 0;
+               res = run_agi(chan, args.argv[0], &agi, pid, &status, dead, args.argc, args.argv);
+               /* If the fork'd process returns non-zero, set AGISTATUS to FAILURE */
+               if ((res == AGI_RESULT_SUCCESS || res == AGI_RESULT_SUCCESS_FAST) && status)
+                       res = AGI_RESULT_FAILURE;
+               if (fds[1] != fds[0])
+                       close(fds[1]);
                if (efd > -1)
                        close(efd);
+               ast_unreplace_sigchld();
        }
-       ast_localuser_remove(me, u);
-       return res;
+       ast_module_user_remove(u);
+
+       switch (res) {
+       case AGI_RESULT_SUCCESS:
+       case AGI_RESULT_SUCCESS_FAST:
+               pbx_builtin_setvar_helper(chan, "AGISTATUS", "SUCCESS");
+               break;
+       case AGI_RESULT_FAILURE:
+               pbx_builtin_setvar_helper(chan, "AGISTATUS", "FAILURE");
+               break;
+       case AGI_RESULT_NOTFOUND:
+               pbx_builtin_setvar_helper(chan, "AGISTATUS", "NOTFOUND");
+               break;
+       case AGI_RESULT_HANGUP:
+               pbx_builtin_setvar_helper(chan, "AGISTATUS", "HANGUP");
+               return -1;
+       }
+
+       return 0;
 }
 
 static int agi_exec(struct ast_channel *chan, void *data)
 {
-       if (chan->_softhangup)
-               ast_log(LOG_WARNING, "If you want to run AGI on hungup channels you should use DeadAGI!\n");
-       return agi_exec_full(chan, data, 0, 0);
+       if (!ast_check_hangup(chan))
+               return agi_exec_full(chan, data, 0, 0);
+       else
+               return agi_exec_full(chan, data, 0, 1);
 }
 
 static int eagi_exec(struct ast_channel *chan, void *data)
 {
-       int readformat;
-       int res;
+       int readformat, res;
 
-       if (chan->_softhangup)
-               ast_log(LOG_WARNING, "If you want to run AGI on hungup channels you should use DeadAGI!\n");
+       if (ast_check_hangup(chan)) {
+               ast_log(LOG_ERROR, "If you want to run AGI on hungup channels you should use DeadAGI!\n");
+               return 0;
+       }
        readformat = chan->readformat;
        if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
                ast_log(LOG_WARNING, "Unable to set channel '%s' to linear mode\n", chan->name);
@@ -2007,58 +2204,35 @@ static int eagi_exec(struct ast_channel *chan, void *data)
 
 static int deadagi_exec(struct ast_channel *chan, void *data)
 {
-       return agi_exec_full(chan, data, 0, 1);
+       ast_log(LOG_WARNING, "DeadAGI has been deprecated, please use AGI in all cases!");
+       return agi_exec(chan, data);
 }
 
-static char showagi_help[] =
-"Usage: show agi [topic]\n"
-"       When called with a topic as an argument, displays usage\n"
-"       information on the given command.  If called without a\n"
-"       topic, it provides a list of AGI commands.\n";
-
-
-static char dumpagihtml_help[] =
-"Usage: dump agihtml <filename>\n"
-"      Dumps the agi command list in html format to given filename\n";
-
-static struct ast_cli_entry showagi = 
-{ { "show", "agi", NULL }, handle_showagi, "Show AGI commands or specific help", showagi_help };
-
-static struct ast_cli_entry dumpagihtml = 
-{ { "dump", "agihtml", NULL }, handle_dumpagihtml, "Dumps a list of agi command in html format", dumpagihtml_help };
+static struct ast_cli_entry cli_agi[] = {
+       AST_CLI_DEFINE(handle_cli_agi_debug,    "Enable/Disable AGI debugging"),
+       AST_CLI_DEFINE(handle_cli_agi_show,     "List AGI commands or specific help"),
+       AST_CLI_DEFINE(handle_cli_agi_dumphtml, "Dumps a list of AGI commands in HTML format")
+};
 
-static int unload_module(void *mod)
+static int unload_module(void)
 {
-       ast_hangup_localusers(mod);
-       ast_cli_unregister(&showagi);
-       ast_cli_unregister(&dumpagihtml);
-       ast_cli_unregister(&cli_debug);
-       ast_cli_unregister(&cli_no_debug);
+       ast_cli_unregister_multiple(cli_agi, sizeof(cli_agi) / sizeof(struct ast_cli_entry));
+       ast_agi_unregister_multiple(ast_module_info->self, commands, sizeof(commands) / sizeof(struct agi_command));
        ast_unregister_application(eapp);
        ast_unregister_application(deadapp);
        return ast_unregister_application(app);
 }
 
-static int load_module(void *mod)
+static int load_module(void)
 {
-       me = mod;
-       ast_cli_register(&showagi);
-       ast_cli_register(&dumpagihtml);
-       ast_cli_register(&cli_debug);
-       ast_cli_register(&cli_no_debug);
+       ast_cli_register_multiple(cli_agi, sizeof(cli_agi) / sizeof(struct ast_cli_entry));
+       ast_agi_register_multiple(ast_module_info->self, commands, sizeof(commands) / sizeof(struct agi_command));
        ast_register_application(deadapp, deadagi_exec, deadsynopsis, descrip);
        ast_register_application(eapp, eagi_exec, esynopsis, descrip);
        return ast_register_application(app, agi_exec, synopsis, descrip);
 }
 
-static const char *description(void)
-{
-       return "Asterisk Gateway Interface (AGI)";
-}
-
-static const char *key(void)
-{
-       return ASTERISK_GPL_KEY;
-}
-
-STD_MOD(MOD_0, NULL, NULL, NULL);
+AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Asterisk Gateway Interface (AGI)",
+               .load = load_module,
+               .unload = unload_module,
+               );