make datastore creation and destruction a generic API since it is not really channel...
[asterisk/asterisk.git] / res / res_agi.c
index d8bca50..8cfc391 100644 (file)
  *
  * \brief AGI - the Asterisk Gateway Interface
  *
- * \author Mark Spencer <markster@digium.com> 
+ * \author Mark Spencer <markster@digium.com>
  */
 
 #include "asterisk.h"
 
 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 
-#include <sys/types.h>
-#include <netdb.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <arpa/inet.h>
 #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 <sys/wait.h>
 #include <sys/stat.h>
+#include <pthread.h>
 
+#include "asterisk/paths.h"    /* use many ast_config_AST_*_DIR */
+#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"
@@ -65,6 +52,10 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/lock.h"
 #include "asterisk/strings.h"
 #include "asterisk/agi.h"
+#include "asterisk/manager.h"
+#include "asterisk/ast_version.h"
+#include "asterisk/speech.h"
+#include "asterisk/manager.h"
 
 #define MAX_ARGS 128
 #define AGI_NANDFS_RETRY 3
@@ -97,7 +88,7 @@ static char *descrip =
 "  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";
+"                    text string, one of SUCCESS | FAILURE | NOTFOUND | HANGUP\n";
 
 static int agidebug = 0;
 
@@ -109,8 +100,10 @@ static int agidebug = 0;
 #define AGI_PORT 4573
 
 enum agi_result {
+       AGI_RESULT_FAILURE = -1,
        AGI_RESULT_SUCCESS,
-       AGI_RESULT_FAILURE,
+       AGI_RESULT_SUCCESS_FAST,
+       AGI_RESULT_SUCCESS_ASYNC,
        AGI_RESULT_NOTFOUND,
        AGI_RESULT_HANGUP,
 };
@@ -120,7 +113,7 @@ static agi_command *find_command(char *cmds[], int exact);
 AST_THREADSTORAGE(agi_buf);
 #define AGI_BUF_INITSIZE 256
 
-int ast_agi_fdprintf(int fd, char *fmt, ...)
+int ast_agi_fdprintf(struct ast_channel *chan, int fd, char *fmt, ...)
 {
        int res = 0;
        va_list ap;
@@ -138,12 +131,385 @@ int ast_agi_fdprintf(int fd, char *fmt, ...)
                return -1;
        }
 
-       if (agidebug)
-               ast_verbose("AGI Tx >> %s", buf->str);
+       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);
 }
 
+/* linked list of AGI commands ready to be executed by Async AGI */
+struct agi_cmd {
+       char *cmd_buffer;
+       char *cmd_id;
+       AST_LIST_ENTRY(agi_cmd) entry;
+};
+
+static void free_agi_cmd(struct agi_cmd *cmd)
+{
+       ast_free(cmd->cmd_buffer);
+       ast_free(cmd->cmd_id);
+       ast_free(cmd);
+}
+
+/* AGI datastore destructor */
+static void agi_destroy_commands_cb(void *data)
+{
+       struct agi_cmd *cmd;
+       AST_LIST_HEAD(, agi_cmd) *chan_cmds = data;
+       AST_LIST_LOCK(chan_cmds);
+       while ( (cmd = AST_LIST_REMOVE_HEAD(chan_cmds, entry)) ) {
+               free_agi_cmd(cmd);
+       }
+       AST_LIST_UNLOCK(chan_cmds);
+       AST_LIST_HEAD_DESTROY(chan_cmds);
+       ast_free(chan_cmds);
+}
+
+/* channel datastore to keep the queue of AGI commands in the channel */
+static const struct ast_datastore_info agi_commands_datastore_info = {
+       .type = "AsyncAGI",
+       .destroy = agi_destroy_commands_cb
+};
+
+static const char mandescr_asyncagi[] =
+"Description: Add an AGI command to the execute queue of the channel in Async AGI\n"
+"Variables:\n"
+"  *Channel: Channel that is currently in Async AGI\n"
+"  *Command: Application to execute\n"
+"   CommandID: comand id. This will be sent back in CommandID header of AsyncAGI exec event notification\n"
+"\n";
+
+static struct agi_cmd *get_agi_cmd(struct ast_channel *chan)
+{
+       struct ast_datastore *store;
+       struct agi_cmd *cmd;
+       AST_LIST_HEAD(, agi_cmd) *agi_commands;
+
+       ast_channel_lock(chan);
+       store = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
+       ast_channel_unlock(chan);
+       if (!store) {
+               ast_log(LOG_ERROR, "Hu? datastore disappeared at Async AGI on Channel %s!\n", chan->name);
+               return NULL;
+       }
+       agi_commands = store->data;
+       AST_LIST_LOCK(agi_commands);
+       cmd = AST_LIST_REMOVE_HEAD(agi_commands, entry);
+       AST_LIST_UNLOCK(agi_commands);
+       return cmd;
+}
+
+/* channel is locked when calling this one either from the CLI or manager thread */
+static int add_agi_cmd(struct ast_channel *chan, const char *cmd_buff, const char *cmd_id)
+{
+       struct ast_datastore *store;
+       struct agi_cmd *cmd;
+       AST_LIST_HEAD(, agi_cmd) *agi_commands;
+
+       store = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
+       if (!store) {
+               ast_log(LOG_WARNING, "Channel %s is not at Async AGI.\n", chan->name);
+               return -1;
+       }
+       agi_commands = store->data;
+       cmd = ast_calloc(1, sizeof(*cmd));
+       if (!cmd) {
+               return -1;
+       }
+       cmd->cmd_buffer = ast_strdup(cmd_buff);
+       if (!cmd->cmd_buffer) {
+               ast_free(cmd);
+               return -1;
+       }
+       cmd->cmd_id = ast_strdup(cmd_id);
+       if (!cmd->cmd_id) {
+               ast_free(cmd->cmd_buffer);
+               ast_free(cmd);
+               return -1;
+       }
+       AST_LIST_LOCK(agi_commands);
+       AST_LIST_INSERT_TAIL(agi_commands, cmd, entry);
+       AST_LIST_UNLOCK(agi_commands);
+       return 0;
+}
+
+static int add_to_agi(struct ast_channel *chan)
+{
+       struct ast_datastore *datastore;
+       AST_LIST_HEAD(, agi_cmd) *agi_cmds_list;
+
+       /* check if already on AGI */
+       ast_channel_lock(chan);
+       datastore = ast_channel_datastore_find(chan, &agi_commands_datastore_info, NULL);
+       ast_channel_unlock(chan);
+       if (datastore) {
+               /* we already have an AGI datastore, let's just
+                  return success */
+               return 0;
+       }
+
+       /* the channel has never been on Async AGI,
+          let's allocate it's datastore */
+       datastore = ast_datastore_alloc(&agi_commands_datastore_info, "AGI");
+       if (!datastore) {
+               return -1;
+       }
+       agi_cmds_list = ast_calloc(1, sizeof(*agi_cmds_list));
+       if (!agi_cmds_list) {
+               ast_log(LOG_ERROR, "Unable to allocate Async AGI commands list.\n");
+               ast_datastore_free(datastore);
+               return -1;
+       }
+       datastore->data = agi_cmds_list;
+       AST_LIST_HEAD_INIT(agi_cmds_list);
+       ast_channel_lock(chan);
+       ast_channel_datastore_add(chan, datastore);
+       ast_channel_unlock(chan);
+       return 0;
+}
+
+/*!
+ * \brief CLI command to add applications to execute in Async AGI
+ * \param e
+ * \param cmd
+ * \param a
+ *
+ * \retval CLI_SUCCESS on success
+ * \retval NULL when init or tab completion is used
+*/
+static char *handle_cli_agi_add_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       struct ast_channel *chan;
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "agi exec";
+               e->usage = "Usage: agi exec <channel name> <app and arguments> [id]\n"
+                          "       Add AGI command to the execute queue of the specified channel in Async AGI\n";
+               return NULL;
+       case CLI_GENERATE:
+               if (a->pos == 2)
+                       return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
+               return NULL;
+       }
+
+       if (a->argc < 4)
+               return CLI_SHOWUSAGE;
+       chan = ast_get_channel_by_name_locked(a->argv[2]);
+       if (!chan) {
+               ast_log(LOG_WARNING, "Channel %s does not exists or cannot lock it\n", a->argv[2]);
+               return CLI_FAILURE;
+       }
+       if (add_agi_cmd(chan, a->argv[3], (a->argc > 4 ? a->argv[4] : ""))) {
+               ast_log(LOG_WARNING, "failed to add AGI command to queue of channel %s\n", chan->name);
+               ast_channel_unlock(chan);
+               return CLI_FAILURE;
+       }
+       ast_log(LOG_DEBUG, "Added AGI command to channel %s queue\n", chan->name);
+       ast_channel_unlock(chan);
+       return CLI_SUCCESS;
+}
+
+/*!
+ * \brief Add a new command to execute by the Async AGI application
+ * \param s
+ * \param m
+ *
+ * It will append the application to the specified channel's queue
+ * if the channel is not inside Async AGI application it will return an error
+ * \retval 0 on success or incorrect use
+ * \retval 1 on failure to add the command ( most likely because the channel
+ * is not in Async AGI loop )
+*/
+static int action_add_agi_cmd(struct mansession *s, const struct message *m)
+{
+       const char *channel = astman_get_header(m, "Channel");
+       const char *cmdbuff = astman_get_header(m, "Command");
+       const char *cmdid   = astman_get_header(m, "CommandID");
+       struct ast_channel *chan;
+       char buf[256];
+       if (ast_strlen_zero(channel) || ast_strlen_zero(cmdbuff)) {
+               astman_send_error(s, m, "Both, Channel and Command are *required*");
+               return 0;
+       }
+       chan = ast_get_channel_by_name_locked(channel);
+       if (!chan) {
+               snprintf(buf, sizeof(buf), "Channel %s does not exists or cannot get its lock", channel);
+               astman_send_error(s, m, buf);
+               return 0;
+       }
+       if (add_agi_cmd(chan, cmdbuff, cmdid)) {
+               snprintf(buf, sizeof(buf), "Failed to add AGI command to channel %s queue", chan->name);
+               astman_send_error(s, m, buf);
+               ast_channel_unlock(chan);
+               return 0;
+       }
+       astman_send_ack(s, m, "Added AGI command to queue");
+       ast_channel_unlock(chan);
+       return 0;
+}
+
+static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int dead);
+static void setup_env(struct ast_channel *chan, char *request, int fd, int enhanced, int argc, char *argv[]);
+static enum agi_result launch_asyncagi(struct ast_channel *chan, char *argv[], int *efd)
+{
+/* This buffer sizes might cause truncation if the AGI command writes more data
+   than AGI_BUF_SIZE as result. But let's be serious, is there an AGI command
+   that writes a response larger than 1024 bytes?, I don't think so, most of
+   them are just result=blah stuff. However probably if GET VARIABLE is called
+   and the variable has large amount of data, that could be a problem. We could
+   make this buffers dynamic, but let's leave that as a second step.
+
+   AMI_BUF_SIZE is twice AGI_BUF_SIZE just for the sake of choosing a safe
+   number. Some characters of AGI buf will be url encoded to be sent to manager
+   clients.  An URL encoded character will take 3 bytes, but again, to cause
+   truncation more than about 70% of the AGI buffer should be URL encoded for
+   that to happen.  Not likely at all.
+
+   On the other hand. I wonder if read() could eventually return less data than
+   the amount already available in the pipe? If so, how to deal with that?
+   So far, my tests on Linux have not had any problems.
+ */
+#define AGI_BUF_SIZE 1024
+#define AMI_BUF_SIZE 2048
+       struct ast_frame *f;
+       struct agi_cmd *cmd;
+       int res, fds[2];
+       int timeout = 100;
+       char agi_buffer[AGI_BUF_SIZE + 1];
+       char ami_buffer[AMI_BUF_SIZE];
+       enum agi_result returnstatus = AGI_RESULT_SUCCESS_ASYNC;
+       AGI async_agi;
+
+       if (efd) {
+               ast_log(LOG_WARNING, "Async AGI does not support Enhanced AGI yet\n");
+               return AGI_RESULT_FAILURE;
+       }
+
+       /* add AsyncAGI datastore to the channel */
+       if (add_to_agi(chan)) {
+               ast_log(LOG_ERROR, "failed to start Async AGI on channel %s\n", chan->name);
+               return AGI_RESULT_FAILURE;
+       }
+
+       /* this pipe allows us to create a "fake" AGI struct to use
+          the AGI commands */
+       res = pipe(fds);
+       if (res) {
+               ast_log(LOG_ERROR, "failed to create Async AGI pipe\n");
+               /* intentionally do not remove datastore, added with
+                  add_to_agi(), from channel. It will be removed when
+                  the channel is hung up anyways */
+               return AGI_RESULT_FAILURE;
+       }
+
+       /* handlers will get the pipe write fd and we read the AGI responses
+          from the pipe read fd */
+       async_agi.fd = fds[1];
+       async_agi.ctrl = fds[1];
+       async_agi.audio = -1; /* no audio support */
+       async_agi.fast = 0;
+
+       /* notify possible manager users of a new channel ready to
+          receive commands */
+       setup_env(chan, "async", fds[1], 0, 0, NULL);
+       /* read the environment */
+       res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
+       if (!res) {
+               ast_log(LOG_ERROR, "failed to read from Async AGI pipe on channel %s\n", chan->name);
+               returnstatus = AGI_RESULT_FAILURE;
+               goto quit;
+       }
+       agi_buffer[res] = '\0';
+       /* encode it and send it thru the manager so whoever is going to take
+          care of AGI commands on this channel can decide which AGI commands
+          to execute based on the setup info */
+       ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, 1);
+       manager_event(EVENT_FLAG_CALL, "AsyncAGI", "SubEvent: Start\r\nChannel: %s\r\nEnv: %s\r\n", chan->name, ami_buffer);
+       while (1) {
+               /* bail out if we need to hangup */
+               if (ast_check_hangup(chan)) {
+                       ast_log(LOG_DEBUG, "ast_check_hangup returned true on chan %s\n", chan->name);
+                       break;
+               }
+               /* retrieve a command
+                  (commands are added via the manager or the cli threads) */
+               cmd = get_agi_cmd(chan);
+               if (cmd) {
+                       /* OK, we have a command, let's call the
+                          command handler. */
+                       res = agi_handle_command(chan, &async_agi, cmd->cmd_buffer, 0);
+                       if ((res < 0) || (res == AST_PBX_KEEPALIVE)) {
+                               free_agi_cmd(cmd);
+                               break;
+                       }
+                       /* the command handler must have written to our fake
+                          AGI struct fd (the pipe), let's read the response */
+                       res = read(fds[0], agi_buffer, AGI_BUF_SIZE);
+                       if (!res) {
+                               returnstatus = AGI_RESULT_FAILURE;
+                               ast_log(LOG_ERROR, "failed to read from AsyncAGI pipe on channel %s\n", chan->name);
+                               free_agi_cmd(cmd);
+                               break;
+                       }
+                       /* we have a response, let's send the response thru the
+                          manager. Include the CommandID if it was specified
+                          when the command was added */
+                       agi_buffer[res] = '\0';
+                       ast_uri_encode(agi_buffer, ami_buffer, AMI_BUF_SIZE, 1);
+                       if (ast_strlen_zero(cmd->cmd_id))
+                               manager_event(EVENT_FLAG_CALL, "AsyncAGI", "SubEvent: Exec\r\nChannel: %s\r\nResult: %s\r\n", chan->name, ami_buffer);
+                       else
+                               manager_event(EVENT_FLAG_CALL, "AsyncAGI", "SubEvent: Exec\r\nChannel: %s\r\nCommandID: %s\r\nResult: %s\r\n", chan->name, cmd->cmd_id, ami_buffer);
+                       free_agi_cmd(cmd);
+               } else {
+                       /* no command so far, wait a bit for a frame to read */
+                       res = ast_waitfor(chan, timeout);
+                       if (res < 0) {
+                               ast_log(LOG_DEBUG, "ast_waitfor returned <= 0 on chan %s\n", chan->name);
+                               break;
+                       }
+                       if (res == 0)
+                               continue;
+                       f = ast_read(chan);
+                       if (!f) {
+                               ast_log(LOG_DEBUG, "No frame read on channel %s, going out ...\n", chan->name);
+                               returnstatus = AGI_RESULT_HANGUP;
+                               break;
+                       }
+                       /* is there any other frame we should care about
+                          besides AST_CONTROL_HANGUP? */
+                       if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
+                               ast_log(LOG_DEBUG, "Got HANGUP frame on channel %s, going out ...\n", chan->name);
+                               ast_frfree(f);
+                               break;
+                       }
+                       ast_frfree(f);
+               }
+       }
+quit:
+       /* notify manager users this channel cannot be
+          controlled anymore by Async AGI */
+       manager_event(EVENT_FLAG_CALL, "AsyncAGI", "SubEvent: End\r\nChannel: %s\r\n", chan->name);
+
+       /* close the pipe */
+       close(fds[0]);
+       close(fds[1]);
+
+       /* intentionally don't get rid of the datastore. So commands can be
+          still in the queue in case AsyncAGI gets called again.
+          Datastore destructor will be called on channel destroy anyway  */
+
+       return returnstatus;
+
+#undef AGI_BUF_SIZE
+#undef AMI_BUF_SIZE
+}
+
 /* launch_netscript: The fastagi handler.
        FastAGI defaults to port 4573 */
 static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds, int *efd, int *opid)
@@ -214,7 +580,7 @@ static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds, in
                }
        }
 
-       if (ast_agi_fdprintf(s, "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);
@@ -225,25 +591,26 @@ static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds, in
        /* 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))
-               ast_agi_fdprintf(s, "agi_network_script: %s\n", script);
+               ast_agi_fdprintf(NULL, s, "agi_network_script: %s\n", script);
 
        ast_debug(4, "Wow, connected!\n");
        fds[0] = s;
        fds[1] = s;
        *opid = -1;
-       return AGI_RESULT_SUCCESS;
+       return AGI_RESULT_SUCCESS_FAST;
 }
 
-static enum agi_result launch_script(char *script, char *argv[], int *fds, int *efd, int *opid)
+static enum agi_result launch_script(struct ast_channel *chan, char *script, char *argv[], int *fds, int *efd, int *opid)
 {
        char tmp[256];
-       int pid, toast[2], fromast[2], audio[2], x, res;
-       sigset_t signal_set, old_set;
+       int pid, toast[2], fromast[2], audio[2], res;
        struct stat st;
 
        if (!strncasecmp(script, "agi://", 6))
                return launch_netscript(script, argv, fds, efd, opid);
-       
+       if (!strncasecmp(script, "agi:async", sizeof("agi:async")-1))
+               return launch_asyncagi(chan, argv, efd);
+
        if (script[0] != '/') {
                snprintf(tmp, sizeof(tmp), "%s/%s", ast_config_AST_AGI_DIR, script);
                script = tmp;
@@ -275,7 +642,7 @@ static enum agi_result launch_script(char *script, char *argv[], int *fds, int *
                        return AGI_RESULT_FAILURE;
                }
                res = fcntl(audio[1], F_GETFL);
-               if (res > -1) 
+               if (res > -1)
                        res = fcntl(audio[1], F_SETFL, res | O_NONBLOCK);
                if (res < 0) {
                        ast_log(LOG_WARNING, "unable to set audio pipe parameters: %s\n", strerror(errno));
@@ -289,12 +656,8 @@ static enum agi_result launch_script(char *script, char *argv[], int *fds, int *
                }
        }
 
-       /* Block SIGHUP during the fork - prevents a race */
-       sigfillset(&signal_set);
-       pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
-       if ((pid = fork()) < 0) {
+       if ((pid = ast_safe_fork(1)) < 0) {
                ast_log(LOG_WARNING, "Failed to fork(): %s\n", strerror(errno));
-               pthread_sigmask(SIG_SETMASK, &old_set, NULL);
                return AGI_RESULT_FAILURE;
        }
        if (!pid) {
@@ -322,34 +685,19 @@ static enum agi_result launch_script(char *script, char *argv[], int *fds, int *
                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 (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
-                       ast_log(LOG_WARNING, "unable to unblock signals for AGI script: %s\n", strerror(errno));
-                       _exit(1);
-               }
-
                /* Close everything but stdin/out/error */
-               for (x = STDERR_FILENO + 2; x < 1024; x++) 
-                       close(x);
+               ast_close_fds_above_n(STDERR_FILENO + 1);
 
                /* 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));
+               ast_child_verbose(1, "Failed to execute '%s': %s", script, strerror(errno));
+               /* Special case to set status of AGI to failure */
+               fprintf(stdout, "failure\n");
                fflush(stdout);
                _exit(1);
        }
-       pthread_sigmask(SIG_SETMASK, &old_set, NULL);
        ast_verb(3, "Launched AGI Script %s\n", script);
        fds[0] = toast[0];
        fds[1] = fromast[1];
@@ -372,38 +720,40 @@ static void setup_env(struct ast_channel *chan, char *request, int fd, int enhan
 
        /* Print initial environment, with agi_request always being the first
           thing */
-       ast_agi_fdprintf(fd, "agi_request: %s\n", request);
-       ast_agi_fdprintf(fd, "agi_channel: %s\n", chan->name);
-       ast_agi_fdprintf(fd, "agi_language: %s\n", chan->language);
-       ast_agi_fdprintf(fd, "agi_type: %s\n", chan->tech->type);
-       ast_agi_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);
+       ast_agi_fdprintf(chan, fd, "agi_version: %s\n", ast_get_version());
 
        /* ANI/DNIS */
-       ast_agi_fdprintf(fd, "agi_callerid: %s\n", S_OR(chan->cid.cid_num, "unknown"));
-       ast_agi_fdprintf(fd, "agi_calleridname: %s\n", S_OR(chan->cid.cid_name, "unknown"));
-       ast_agi_fdprintf(fd, "agi_callingpres: %d\n", chan->cid.cid_pres);
-       ast_agi_fdprintf(fd, "agi_callingani2: %d\n", chan->cid.cid_ani2);
-       ast_agi_fdprintf(fd, "agi_callington: %d\n", chan->cid.cid_ton);
-       ast_agi_fdprintf(fd, "agi_callingtns: %d\n", chan->cid.cid_tns);
-       ast_agi_fdprintf(fd, "agi_dnid: %s\n", S_OR(chan->cid.cid_dnid, "unknown"));
-       ast_agi_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 */
-       ast_agi_fdprintf(fd, "agi_context: %s\n", chan->context);
-       ast_agi_fdprintf(fd, "agi_extension: %s\n", chan->exten);
-       ast_agi_fdprintf(fd, "agi_priority: %d\n", chan->priority);
-       ast_agi_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 */
-       ast_agi_fdprintf(fd, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
+       ast_agi_fdprintf(chan, fd, "agi_accountcode: %s\n", chan->accountcode ? chan->accountcode : "");
+       ast_agi_fdprintf(chan, fd, "agi_threadid: %ld\n", (long)pthread_self());
 
        /* 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(fd, "agi_arg_%d: %s\n", count, argv[count]);
+               ast_agi_fdprintf(chan, fd, "agi_arg_%d: %s\n", count, argv[count]);
 
        /* End with empty return */
-       ast_agi_fdprintf(fd, "\n");
+       ast_agi_fdprintf(chan, fd, "\n");
 }
 
 static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
@@ -414,7 +764,7 @@ static int handle_answer(struct ast_channel *chan, AGI *agi, int argc, char *arg
        if (chan->_state != AST_STATE_UP)
                res = ast_answer(chan);
 
-       ast_agi_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;
 }
 
@@ -427,7 +777,7 @@ static int handle_waitfordigit(struct ast_channel *chan, AGI *agi, int argc, cha
        if (sscanf(argv[3], "%d", &to) != 1)
                return RESULT_SHOWUSAGE;
        res = ast_waitfordigit_full(chan, to, agi->audio, agi->ctrl);
-       ast_agi_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;
 }
 
@@ -446,7 +796,7 @@ 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]);
-       ast_agi_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;
 }
 
@@ -459,32 +809,30 @@ static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, char *a
 
        res = ast_recvchar(chan,atoi(argv[2]));
        if (res == 0) {
-               ast_agi_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) {
-               ast_agi_fdprintf(agi->fd, "200 result=%d\n", res);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
                return RESULT_SUCCESS;
        }
-       else {
-               ast_agi_fdprintf(agi->fd, "200 result=%d (hangup)\n", res);
-               return RESULT_FAILURE;
-       }
+       ast_agi_fdprintf(chan, agi->fd, "200 result=%d (hangup)\n", res);
+       return RESULT_FAILURE;
 }
 
 static int handle_recvtext(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
        char *buf;
-       
+
        if (argc != 3)
                return RESULT_SHOWUSAGE;
 
-       buf = ast_recvtext(chan,atoi(argv[2]));
+       buf = ast_recvtext(chan, atoi(argv[2]));
        if (buf) {
-               ast_agi_fdprintf(agi->fd, "200 result=1 (%s)\n", buf);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s)\n", buf);
                ast_free(buf);
-       } else {        
-               ast_agi_fdprintf(agi->fd, "200 result=-1\n");
+       } else {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=-1\n");
        }
        return RESULT_SUCCESS;
 }
@@ -496,19 +844,23 @@ static int handle_tddmode(struct ast_channel *chan, AGI *agi, int argc, char *ar
        if (argc != 3)
                return RESULT_SHOWUSAGE;
 
-       if (!strncasecmp(argv[2],"on",2)) 
-               x = 1; 
-       else 
+       if (!strncasecmp(argv[2],"on",2)) {
+               x = 1;
+       } else  {
                x = 0;
-       if (!strncasecmp(argv[2],"mate",4)) 
+       }
+       if (!strncasecmp(argv[2],"mate",4))  {
                x = 2;
-       if (!strncasecmp(argv[2],"tdd",3))
+       }
+       if (!strncasecmp(argv[2],"tdd",3)) {
                x = 1;
+       }
        res = ast_channel_setoption(chan, AST_OPTION_TDD, &x, sizeof(char), 0);
-       if (res != RESULT_SUCCESS)
-               ast_agi_fdprintf(agi->fd, "200 result=0\n");
-       else
-               ast_agi_fdprintf(agi->fd, "200 result=1\n");
+       if (res != RESULT_SUCCESS) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+       } else {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
+       }
        return RESULT_SUCCESS;
 }
 
@@ -516,50 +868,50 @@ static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, char *
 {
        int res;
 
-       if (argc != 3)
+       if (argc != 3) {
                return RESULT_SHOWUSAGE;
+       }
 
        res = ast_send_image(chan, argv[2]);
-       if (!ast_check_hangup(chan))
+       if (!ast_check_hangup(chan)) {
                res = 0;
-       ast_agi_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, skipms = 3000;
-       char *fwd = NULL, *rev = NULL, *pause = NULL, *stop = NULL;
+       char *fwd = "#", *rev = "*", *pause = NULL, *stop = NULL;       /* Default values */
 
-       if (argc < 5 || argc > 9)
+       if (argc < 5 || argc > 9) {
                return RESULT_SHOWUSAGE;
+       }
 
-       if (!ast_strlen_zero(argv[4]))
+       if (!ast_strlen_zero(argv[4])) {
                stop = argv[4];
-       else
-               stop = NULL;
-       
-       if ((argc > 5) && (sscanf(argv[5], "%d", &skipms) != 1))
+       }
+
+       if ((argc > 5) && (sscanf(argv[5], "%d", &skipms) != 1)) {
                return RESULT_SHOWUSAGE;
+       }
 
-       if (argc > 6 && !ast_strlen_zero(argv[6]))
+       if (argc > 6 && !ast_strlen_zero(argv[6])) {
                fwd = argv[6];
-       else
-               fwd = "#";
+       }
 
-       if (argc > 7 && !ast_strlen_zero(argv[7]))
+       if (argc > 7 && !ast_strlen_zero(argv[7])) {
                rev = argv[7];
-       else
-               rev = "*";
-       
-       if (argc > 8 && !ast_strlen_zero(argv[8]))
+       }
+
+       if (argc > 8 && !ast_strlen_zero(argv[8])) {
                pause = argv[8];
-       else
-               pause = NULL;
-       
+       }
+
        res = ast_control_streamfile(chan, argv[3], fwd, rev, stop, pause, NULL, skipms, NULL);
-       
-       ast_agi_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;
 }
@@ -574,20 +926,20 @@ static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char
        if (argc < 4 || argc > 5)
                return RESULT_SHOWUSAGE;
 
-       if (argv[3]) 
+       if (argv[3])
                edigits = argv[3];
 
        if ((argc > 4) && (sscanf(argv[4], "%ld", &sample_offset) != 1))
                return RESULT_SHOWUSAGE;
 
        if (!(fs = ast_openstream(chan, argv[2], chan->language))) {
-               ast_agi_fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
+               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);
@@ -599,7 +951,7 @@ static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char
        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 */
@@ -609,11 +961,11 @@ 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;
        }
-       ast_agi_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 */
+/*! \brief 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, vres;
@@ -625,25 +977,25 @@ static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, char *
        if ( argc < 4 || argc > 5 )
                return RESULT_SHOWUSAGE;
 
-       if ( argv[3] ) 
+       if ( argv[3] )
                edigits = argv[3];
 
        if ( argc == 5 )
                timeout = atoi(argv[4]);
-       else if (chan->pbx->dtimeout) {
+       else if (chan->pbx->dtimeoutms) {
                /* by default dtimeout is set to 5sec */
-               timeout = chan->pbx->dtimeout * 1000; /* in msec */
+               timeout = chan->pbx->dtimeoutms; /* in msec */
        }
 
        if (!(fs = ast_openstream(chan, argv[2], chan->language))) {
-               ast_agi_fdprintf(agi->fd, "200 result=%d endpos=%ld\n", 0, sample_offset);
+               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 ((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);
@@ -674,14 +1026,14 @@ static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, char *
                        res=0;
        }
 
-       ast_agi_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;
 }
 
 
 
 
-/*--- handle_saynumber: Say number in various language syntaxes ---*/
+/*! \brief Say number in various language syntaxes */
 /* While waiting, we're sending a NULL.  */
 static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
@@ -694,7 +1046,7 @@ static int handle_saynumber(struct ast_channel *chan, AGI *agi, int argc, char *
        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;
-       ast_agi_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;
 }
 
@@ -710,7 +1062,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;
-       ast_agi_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;
 }
 
@@ -724,7 +1076,7 @@ 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;
-       ast_agi_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;
 }
 
@@ -739,7 +1091,7 @@ 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;
-       ast_agi_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,7 +1106,7 @@ 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;
-       ast_agi_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;
 }
 
@@ -763,7 +1115,7 @@ static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, char
        int res = 0;
        time_t unixtime;
        char *format, *zone = NULL;
-       
+
        if (argc < 4)
                return RESULT_SHOWUSAGE;
 
@@ -774,7 +1126,7 @@ static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, char
                if (!strcasecmp(chan->language, "de")) {
                        format = "A dBY HMS";
                } else {
-                       format = "ABdY 'digits/at' IMp"; 
+                       format = "ABdY 'digits/at' IMp";
                }
        }
 
@@ -788,7 +1140,7 @@ static int handle_saydatetime(struct ast_channel *chan, AGI *agi, int argc, char
        if (res == 1)
                return RESULT_SUCCESS;
 
-       ast_agi_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;
 }
 
@@ -802,7 +1154,7 @@ 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;
-       ast_agi_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;
 }
 
@@ -814,22 +1166,22 @@ static int handle_getdata(struct ast_channel *chan, AGI *agi, int argc, char *ar
        if (argc < 3)
                return RESULT_SHOWUSAGE;
        if (argc >= 4)
-               timeout = atoi(argv[3]); 
+               timeout = atoi(argv[3]);
        else
                timeout = 0;
-       if (argc >= 5) 
-               max = atoi(argv[4]); 
+       if (argc >= 5)
+               max = atoi(argv[4]);
        else
                max = 1024;
        res = ast_app_getdata_full(chan, argv[2], data, max, timeout, agi->audio, agi->ctrl);
        if (res == 2)                   /* New command */
                return RESULT_SUCCESS;
        else if (res == 1)
-               ast_agi_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 )
-               ast_agi_fdprintf(agi->fd, "200 result=-1\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=-1\n");
        else
-               ast_agi_fdprintf(agi->fd, "200 result=%s\n", data);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%s\n", data);
        return RESULT_SUCCESS;
 }
 
@@ -839,16 +1191,16 @@ 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));
-       ast_agi_fdprintf(agi->fd, "200 result=0\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
-       
+
 static int handle_setextension(struct ast_channel *chan, AGI *agi, int argc, char **argv)
 {
        if (argc != 3)
                return RESULT_SHOWUSAGE;
        ast_copy_string(chan->exten, argv[2], sizeof(chan->exten));
-       ast_agi_fdprintf(agi->fd, "200 result=0\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
 
@@ -857,7 +1209,7 @@ static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char
        int pri;
 
        if (argc != 3)
-               return RESULT_SHOWUSAGE;        
+               return RESULT_SHOWUSAGE;
 
        if (sscanf(argv[2], "%d", &pri) != 1) {
                if ((pri = ast_findlabel_extension(chan, chan->context, chan->exten, argv[2], chan->cid.cid_num)) < 1)
@@ -865,10 +1217,10 @@ static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char
        }
 
        ast_explicit_goto(chan, NULL, NULL, pri);
-       ast_agi_fdprintf(agi->fd, "200 result=0\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
-               
+
 static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
        struct ast_filestream *fs;
@@ -883,9 +1235,8 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
        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;
-
+       char *silencestr = NULL;
+       int rfmt = 0;
 
        /* XXX EAGI FIXME XXX */
 
@@ -926,9 +1277,9 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
                        ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
                        return -1;
                }
-               ast_dsp_set_threshold(sildet, 256);
+               ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
        }
-
+       
        /* 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
         * offset */
@@ -941,39 +1292,39 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
        if (!res)
                res = ast_waitstream(chan, argv[4]);
        if (res) {
-               ast_agi_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, AST_FILE_MODE);
                if (!fs) {
                        res = -1;
-                       ast_agi_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 */
                ast_seekstream(fs, sample_offset, SEEK_SET);
                ast_truncstream(fs);
-               
+
                start = ast_tvnow();
                while ((ms < 0) || ast_tvdiff_ms(ast_tvnow(), start) < ms) {
                        res = ast_waitfor(chan, -1);
                        if (res < 0) {
                                ast_closestream(fs);
-                               ast_agi_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) {
-                               ast_agi_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", -1, sample_offset);
                                ast_closestream(fs);
                                if (sildet)
                                        ast_dsp_free(sildet);
@@ -988,7 +1339,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);
-                                       ast_agi_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)
@@ -1028,12 +1379,12 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
                                break;
                }
 
-                       if (gotsilence) {
-                               ast_stream_rewind(fs, silence-1000);
-                               ast_truncstream(fs);
-                               sample_offset = ast_tellstream(fs);
-               }               
-               ast_agi_fdprintf(agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
+               if (gotsilence) {
+                       ast_stream_rewind(fs, silence-1000);
+                       ast_truncstream(fs);
+                       sample_offset = ast_tellstream(fs);
+               }
+               ast_agi_fdprintf(chan, agi->fd, "200 result=%d (timeout) endpos=%ld\n", res, sample_offset);
                ast_closestream(fs);
        }
 
@@ -1041,26 +1392,29 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
                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);
+               ast_dsp_free(sildet);
        }
+
        return RESULT_SUCCESS;
 }
 
 static int handle_autohangup(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
 {
-       int timeout;
+       double timeout;
+       struct timeval whentohangup = { 0, 0 };
 
        if (argc != 3)
                return RESULT_SHOWUSAGE;
-       if (sscanf(argv[2], "%d", &timeout) != 1)
+       if (sscanf(argv[2], "%lf", &timeout) != 1)
                return RESULT_SHOWUSAGE;
        if (timeout < 0)
                timeout = 0;
-       if (timeout)
-               chan->whentohangup = time(NULL) + timeout;
-       else
-               chan->whentohangup = 0;
-       ast_agi_fdprintf(agi->fd, "200 result=0\n");
+       if (timeout) {
+               whentohangup.tv_sec = timeout;
+               whentohangup.tv_usec = (timeout - whentohangup.tv_sec) * 1000000.0;
+       }
+       ast_channel_setwhentohangup_tv(chan, whentohangup);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
 
@@ -1071,7 +1425,7 @@ static int handle_hangup(struct ast_channel *chan, AGI *agi, int argc, char **ar
        if (argc == 1) {
                /* no argument: hangup the current channel */
                ast_softhangup(chan,AST_SOFTHANGUP_EXPLICIT);
-               ast_agi_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 */
@@ -1079,12 +1433,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);
-                       ast_agi_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 */
-               ast_agi_fdprintf(agi->fd, "200 result=-1\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=-1\n");
                return RESULT_SUCCESS;
        } else {
                return RESULT_SHOWUSAGE;
@@ -1102,12 +1456,28 @@ static int handle_exec(struct ast_channel *chan, AGI *agi, int argc, char **argv
        ast_verb(3, "AGI Script Executing Application: (%s) Options: (%s)\n", argv[1], argv[2]);
 
        if ((app = pbx_findapp(argv[1]))) {
-               res = pbx_exec(chan, app, argv[2]);
+               if (ast_compat_res_agi && !ast_strlen_zero(argv[2])) {
+                       char *compat = alloca(strlen(argv[2]) * 2 + 1), *cptr, *vptr;
+                       for (cptr = compat, vptr = argv[2]; *vptr; vptr++) {
+                               if (*vptr == ',') {
+                                       *cptr++ = '\\';
+                                       *cptr++ = ',';
+                               } else if (*vptr == '|') {
+                                       *cptr++ = ',';
+                               } else {
+                                       *cptr++ = *vptr;
+                               }
+                       }
+                       *cptr = '\0';
+                       res = pbx_exec(chan, app, compat);
+               } else {
+                       res = pbx_exec(chan, app, argv[2]);
+               }
        } else {
                ast_log(LOG_WARNING, "Could not find application (%s)\n", argv[1]);
                res = -2;
        }
-       ast_agi_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;
@@ -1130,7 +1500,7 @@ static int handle_setcallerid(struct ast_channel *chan, AGI *agi, int argc, char
                ast_set_callerid(chan, l, n, NULL);
        }
 
-       ast_agi_fdprintf(agi->fd, "200 result=1\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
        return RESULT_SUCCESS;
 }
 
@@ -1139,18 +1509,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 */
-               ast_agi_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) {
-                       ast_agi_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 */
-               ast_agi_fdprintf(agi->fd, "200 result=-1\n");
+               ast_agi_fdprintf(chan, agi->fd, "200 result=-1\n");
                return RESULT_SUCCESS;
        } else {
                return RESULT_SHOWUSAGE;
@@ -1162,7 +1532,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]);
 
-       ast_agi_fdprintf(agi->fd, "200 result=1\n");
+       ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
        return RESULT_SUCCESS;
 }
 
@@ -1182,16 +1552,16 @@ static int handle_getvariable(struct ast_channel *chan, AGI *agi, int argc, char
        }
 
        if (ret)
-               ast_agi_fdprintf(agi->fd, "200 result=1 (%s)\n", ret);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s)\n", ret);
        else
-               ast_agi_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))
@@ -1201,11 +1571,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);
-               ast_agi_fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s)\n", tmp);
        } else {
-               ast_agi_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);
@@ -1215,7 +1585,6 @@ static int handle_getvariablefull(struct ast_channel *chan, AGI *agi, int argc,
 static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **argv)
 {
        int level = 0;
-       char *prefix;
 
        if (argc < 2)
                return RESULT_SHOWUSAGE;
@@ -1223,27 +1592,10 @@ static int handle_verbose(struct ast_channel *chan, AGI *agi, int argc, char **a
        if (argv[2])
                sscanf(argv[2], "%d", &level);
 
-       switch (level) {
-               case 4:
-                       prefix = VERBOSE_PREFIX_4;
-                       break;
-               case 3:
-                       prefix = VERBOSE_PREFIX_3;
-                       break;
-               case 2:
-                       prefix = VERBOSE_PREFIX_2;
-                       break;
-               case 1:
-               default:
-                       prefix = VERBOSE_PREFIX_1;
-                       break;
-       }
+       ast_verb(level, "%s: %s\n", chan->data, argv[1]);
+
+       ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
 
-       if (level <= option_verbose)
-               ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
-       
-       ast_agi_fdprintf(agi->fd, "200 result=1\n");
-       
        return RESULT_SUCCESS;
 }
 
@@ -1255,10 +1607,10 @@ static int handle_dbget(struct ast_channel *chan, AGI *agi, int argc, char **arg
        if (argc != 4)
                return RESULT_SHOWUSAGE;
        res = ast_db_get(argv[2], argv[3], tmp, sizeof(tmp));
-       if (res) 
-               ast_agi_fdprintf(agi->fd, "200 result=0\n");
+       if (res)
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        else
-               ast_agi_fdprintf(agi->fd, "200 result=1 (%s)\n", tmp);
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s)\n", tmp);
 
        return RESULT_SUCCESS;
 }
@@ -1270,7 +1622,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]);
-       ast_agi_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;
 }
 
@@ -1281,7 +1633,7 @@ 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]);
-       ast_agi_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;
 }
 
@@ -1296,52 +1648,346 @@ static int handle_dbdeltree(struct ast_channel *chan, AGI *agi, int argc, char *
        else
                res = ast_db_deltree(argv[2], NULL);
 
-       ast_agi_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 char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "agi set debug [on|off]";
+               e->usage =
+                       "Usage: agi set debug [on|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)
+               return CLI_SHOWUSAGE;
+
+       if (strncasecmp(a->argv[3], "off", 3) == 0) {
+               agidebug = 0;
+       } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
+               agidebug = 1;
+       } else {
+               return CLI_SHOWUSAGE;
+       }
+       ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
+       return CLI_SUCCESS;
+}
+
+static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
+{
+       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, NULL);
+       else if (!strncasecmp(argv[2], "off", 3))
+               ast_moh_stop(chan);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        return RESULT_SUCCESS;
 }
 
-static const char debug_usage[] = 
-"Usage: agi debug\n"
-"       Enables dumping of AGI transactions for debugging purposes\n";
+static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, char **argv)
+{
+       /* If a structure already exists, return an error */
+        if (agi->speech) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+               return RESULT_SUCCESS;
+       }
+
+       if ((agi->speech = ast_speech_new(argv[2], AST_FORMAT_SLINEAR)))
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
+       else
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
 
-static const char no_debug_usage[] = 
-"Usage: agi debug off\n"
-"       Disables dumping of AGI transactions for debugging purposes\n";
+       return RESULT_SUCCESS;
+}
 
-static int agi_do_debug(int fd, int argc, char *argv[])
+static int handle_speechset(struct ast_channel *chan, AGI *agi, int argc, char **argv)
 {
-       if (argc != 2)
+       /* Check for minimum arguments */
+        if (argc != 3)
                return RESULT_SHOWUSAGE;
-       agidebug = 1;
-       ast_cli(fd, "AGI Debugging Enabled\n");
+
+       /* Check to make sure speech structure exists */
+       if (!agi->speech) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+               return RESULT_SUCCESS;
+       }
+
+       ast_speech_change(agi->speech, argv[2], argv[3]);
+       ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
+
        return RESULT_SUCCESS;
 }
 
-static int agi_no_debug(int fd, int argc, char *argv[])
+static int handle_speechdestroy(struct ast_channel *chan, AGI *agi, int argc, char **argv)
 {
-       if (argc != 3)
+       if (agi->speech) {
+               ast_speech_destroy(agi->speech);
+               agi->speech = NULL;
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
+       } else {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+       }
+
+       return RESULT_SUCCESS;
+}
+
+static int handle_speechloadgrammar(struct ast_channel *chan, AGI *agi, int argc, char **argv)
+{
+       if (argc != 5)
                return RESULT_SHOWUSAGE;
-       agidebug = 0;
-       ast_cli(fd, "AGI Debugging Disabled\n");
+
+       if (!agi->speech) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+               return RESULT_SUCCESS;
+       }
+
+       if (ast_speech_grammar_load(agi->speech, argv[3], argv[4]))
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+       else
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
+
        return RESULT_SUCCESS;
 }
 
-static int handle_noop(struct ast_channel *chan, AGI *agi, int arg, char *argv[])
+static int handle_speechunloadgrammar(struct ast_channel *chan, AGI *agi, int argc, char **argv)
 {
-       ast_agi_fdprintf(agi->fd, "200 result=0\n");
+       if (argc != 4)
+               return RESULT_SHOWUSAGE;
+
+       if (!agi->speech) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+               return RESULT_SUCCESS;
+       }
+
+       if (ast_speech_grammar_unload(agi->speech, argv[3]))
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+       else
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
+
        return RESULT_SUCCESS;
 }
 
-static int handle_setmusic(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
+static int handle_speechactivategrammar(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, NULL);
-       else if (!strncasecmp(argv[2], "off", 3))
-               ast_moh_stop(chan);
-       ast_agi_fdprintf(agi->fd, "200 result=0\n");
+       if (argc != 4)
+               return RESULT_SHOWUSAGE;
+
+       if (!agi->speech) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+               return RESULT_SUCCESS;
+       }
+
+       if (ast_speech_grammar_activate(agi->speech, argv[3]))
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+       else
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
+
        return RESULT_SUCCESS;
 }
 
+static int handle_speechdeactivategrammar(struct ast_channel *chan, AGI *agi, int argc, char **argv)
+{
+       if (argc != 4)
+               return RESULT_SHOWUSAGE;
+
+       if (!agi->speech) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+               return RESULT_SUCCESS;
+       }
+
+       if (ast_speech_grammar_deactivate(agi->speech, argv[3]))
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+       else
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
+
+       return RESULT_SUCCESS;
+}
+
+static int speech_streamfile(struct ast_channel *chan, const char *filename, const char *preflang, int offset)
+{
+       struct ast_filestream *fs = NULL;
+
+       if (!(fs = ast_openstream(chan, filename, preflang)))
+               return -1;
+
+       if (offset)
+               ast_seekstream(fs, offset, SEEK_SET);
+
+       if (ast_applystream(chan, fs))
+               return -1;
+
+       if (ast_playstream(fs))
+               return -1;
+
+       return 0;
+}
+
+static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc, char **argv)
+{
+       struct ast_speech *speech = agi->speech;
+       char *prompt, dtmf = 0, tmp[4096] = "", *buf = tmp;
+       int timeout = 0, offset = 0, old_read_format = 0, res = 0, i = 0;
+       long current_offset = 0;
+       const char *reason = NULL;
+       struct ast_frame *fr = NULL;
+       struct ast_speech_result *result = NULL;
+       size_t left = sizeof(tmp);
+       time_t start = 0, current;
+
+       if (argc < 4)
+               return RESULT_SHOWUSAGE;
+
+       if (!speech) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+               return RESULT_SUCCESS;
+       }
+
+       prompt = argv[2];
+       timeout = atoi(argv[3]);
+
+       /* If offset is specified then convert from text to integer */
+       if (argc == 5)
+               offset = atoi(argv[4]);
+
+       /* We want frames coming in signed linear */
+       old_read_format = chan->readformat;
+       if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+               return RESULT_SUCCESS;
+       }
+
+       /* Setup speech structure */
+       if (speech->state == AST_SPEECH_STATE_NOT_READY || speech->state == AST_SPEECH_STATE_DONE) {
+               ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
+               ast_speech_start(speech);
+       }
+
+       /* Start playing prompt */
+       speech_streamfile(chan, prompt, chan->language, offset);
+
+       /* Go into loop reading in frames, passing to speech thingy, checking for hangup, all that jazz */
+       while (ast_strlen_zero(reason)) {
+               /* Run scheduled items */
+                ast_sched_runq(chan->sched);
+
+               /* See maximum time of waiting */
+               if ((res = ast_sched_wait(chan->sched)) < 0)
+                       res = 1000;
+
+               /* Wait for frame */
+               if (ast_waitfor(chan, res) > 0) {
+                       if (!(fr = ast_read(chan))) {
+                               reason = "hangup";
+                               break;
+                       }
+               }
+
+               /* Perform timeout check */
+               if ((timeout > 0) && (start > 0)) {
+                       time(&current);
+                       if ((current - start) >= timeout) {
+                               reason = "timeout";
+                               if (fr)
+                                       ast_frfree(fr);
+                               break;
+                       }
+               }
+
+               /* Check the speech structure for any changes */
+               ast_mutex_lock(&speech->lock);
+
+               /* See if we need to quiet the audio stream playback */
+               if (ast_test_flag(speech, AST_SPEECH_QUIET) && chan->stream) {
+                       current_offset = ast_tellstream(chan->stream);
+                       ast_stopstream(chan);
+                       ast_clear_flag(speech, AST_SPEECH_QUIET);
+               }
+
+               /* Check each state */
+               switch (speech->state) {
+               case AST_SPEECH_STATE_READY:
+                       /* If the stream is done, start timeout calculation */
+                       if ((timeout > 0) && ((!chan->stream) || (chan->streamid == -1 && chan->timingfunc == NULL))) {
+                               ast_stopstream(chan);
+                               time(&start);
+                       }
+                       /* Write audio frame data into speech engine if possible */
+                       if (fr && fr->frametype == AST_FRAME_VOICE)
+                               ast_speech_write(speech, fr->data.ptr, fr->datalen);
+                       break;
+               case AST_SPEECH_STATE_WAIT:
+                       /* Cue waiting sound if not already playing */
+                       if ((!chan->stream) || (chan->streamid == -1 && chan->timingfunc == NULL)) {
+                               ast_stopstream(chan);
+                               /* If a processing sound exists, or is not none - play it */
+                               if (!ast_strlen_zero(speech->processing_sound) && strcasecmp(speech->processing_sound, "none"))
+                                       speech_streamfile(chan, speech->processing_sound, chan->language, 0);
+                       }
+                       break;
+               case AST_SPEECH_STATE_DONE:
+                       /* Get the results */
+                       speech->results = ast_speech_results_get(speech);
+                       /* Change state to not ready */
+                       ast_speech_change_state(speech, AST_SPEECH_STATE_NOT_READY);
+                       reason = "speech";
+                       break;
+               default:
+                       break;
+               }
+               ast_mutex_unlock(&speech->lock);
+
+               /* Check frame for DTMF or hangup */
+               if (fr) {
+                       if (fr->frametype == AST_FRAME_DTMF) {
+                               reason = "dtmf";
+                               dtmf = fr->subclass;
+                       } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_HANGUP) {
+                               reason = "hangup";
+                       }
+                       ast_frfree(fr);
+               }
+       }
+
+       if (!strcasecmp(reason, "speech")) {
+               /* Build string containing speech results */
+                for (result = speech->results; result; result = AST_LIST_NEXT(result, list)) {
+                       /* Build result string */
+                       ast_build_string(&buf, &left, "%sscore%d=%d text%d=\"%s\" grammar%d=%s", (i > 0 ? " " : ""), i, result->score, i, result->text, i, result->grammar);
+                        /* Increment result count */
+                       i++;
+               }
+                /* Print out */
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (speech) endpos=%ld results=%d %s\n", current_offset, i, tmp);
+       } else if (!strcasecmp(reason, "dtmf")) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (digit) digit=%c endpos=%ld\n", dtmf, current_offset);
+       } else if (!strcasecmp(reason, "hangup") || !strcasecmp(reason, "timeout")) {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s) endpos=%ld\n", reason, current_offset);
+       } else {
+               ast_agi_fdprintf(chan, agi->fd, "200 result=0 endpos=%ld\n", current_offset);
+       }
+
+       return RESULT_SUCCESS;
+}
+
+static int handle_asyncagi_break(struct ast_channel *chan, AGI *agi, int argc, char *argv[])
+{
+       ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
+       return AST_PBX_KEEPALIVE;
+}
+
 static char usage_setmusic[] =
 " Usage: SET MUSIC ON <on|off> <class>\n"
 "      Enables/Disables the music on hold generator.  If <class> is\n"
@@ -1398,7 +2044,7 @@ static char usage_setvariable[] =
 
 static char usage_channelstatus[] =
 " Usage: CHANNEL STATUS [<channelname>]\n"
-"      Returns the status of the specified channel.\n" 
+"      Returns the status of the specified channel.\n"
 " If no channel name is given the returns the status of the\n"
 " current channel.  Return values:\n"
 "  0 Channel is down and available\n"
@@ -1424,12 +2070,12 @@ static char usage_hangup[] =
 "      Hangs up the specified channel.\n"
 " If no channel name is given, hangs up the current channel\n";
 
-static char usage_answer[] = 
+static char usage_answer[] =
 " Usage: ANSWER\n"
 "      Answers channel if not already in answer state. Returns -1 on\n"
 " channel failure, or 0 if successful.\n";
 
-static char usage_waitfordigit[] = 
+static char usage_waitfordigit[] =
 " Usage: WAIT FOR DIGIT <timeout>\n"
 "      Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.\n"
 " Returns -1 on channel failure, 0 if no digit is received in the timeout, or\n"
@@ -1490,7 +2136,7 @@ static char usage_controlstreamfile[] =
 " extension must not be included in the filename.\n\n"
 " Note: ffchar and rewchar default to * and # respectively.\n";
 
-static char usage_getoption[] = 
+static char usage_getoption[] =
 " Usage: GET OPTION <filename> <escape_digits> [timeout]\n"
 "      Behaves similar to STREAM FILE but used with a timeout option.\n";
 
@@ -1585,10 +2231,46 @@ static char usage_autohangup[] =
 " future.  Of course it can be hungup before then as well. Setting to 0 will\n"
 " cause the autohangup feature to be disabled on this channel.\n";
 
+static char usage_break_aagi[] =
+" Usage: ASYNCAGI BREAK\n"
+"      Break the Async AGI loop.\n";
+
 static char usage_noop[] =
 " Usage: NoOp\n"
 "      Does nothing.\n";
 
+static char usage_speechcreate[] =
+" Usage: SPEECH CREATE <engine>\n"
+"       Create a speech object to be used by the other Speech AGI commands.\n";
+
+static char usage_speechset[] =
+" Usage: SPEECH SET <name> <value>\n"
+"       Set an engine-specific setting.\n";
+
+static char usage_speechdestroy[] =
+" Usage: SPEECH DESTROY\n"
+"       Destroy the speech object created by SPEECH CREATE.\n";
+
+static char usage_speechloadgrammar[] =
+" Usage: SPEECH LOAD GRAMMAR <grammar name> <path to grammar>\n"
+"       Loads the specified grammar as the specified name.\n";
+
+static char usage_speechunloadgrammar[] =
+" Usage: SPEECH UNLOAD GRAMMAR <grammar name>\n"
+"       Unloads the specified grammar.\n";
+
+static char usage_speechactivategrammar[] =
+" Usage: SPEECH ACTIVATE GRAMMAR <grammar name>\n"
+"       Activates the specified grammar on the speech object.\n";
+
+static char usage_speechdeactivategrammar[] =
+" Usage: SPEECH DEACTIVATE GRAMMAR <grammar name>\n"
+"       Deactivates the specified grammar on the speech object.\n";
+
+static char usage_speechrecognize[] =
+" Usage: SPEECH RECOGNIZE <prompt> <timeout> [<offset>]\n"
+"       Plays back given prompt while listening for speech and dtmf.\n";
+
 /*!
  * \brief AGI commands list
  */
@@ -1630,11 +2312,20 @@ static struct agi_command commands[] = {
        { { "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 },
+       { { "speech", "create", NULL }, handle_speechcreate, "Creates a speech object", usage_speechcreate, 0 },
+       { { "speech", "set", NULL }, handle_speechset, "Sets a speech engine setting", usage_speechset, 0 },
+       { { "speech", "destroy", NULL }, handle_speechdestroy, "Destroys a speech object", usage_speechdestroy, 1 },
+       { { "speech", "load", "grammar", NULL }, handle_speechloadgrammar, "Loads a grammar", usage_speechloadgrammar, 0 },
+       { { "speech", "unload", "grammar", NULL }, handle_speechunloadgrammar, "Unloads a grammar", usage_speechunloadgrammar, 1 },
+       { { "speech", "activate", "grammar", NULL }, handle_speechactivategrammar, "Activates a grammar", usage_speechactivategrammar, 0 },
+       { { "speech", "deactivate", "grammar", NULL }, handle_speechdeactivategrammar, "Deactivates a grammar", usage_speechdeactivategrammar, 0 },
+       { { "speech", "recognize", NULL }, handle_speechrecognize, "Recognizes speech", usage_speechrecognize, 0 },
+       { { "asyncagi", "break", NULL }, handle_asyncagi_break, "Break AsyncAGI loop", usage_break_aagi, 0 },
 };
 
 static AST_RWLIST_HEAD_STATIC(agi_commands, agi_command);
 
-static int help_workhorse(int fd, char *match[])
+static char *help_workhorse(int fd, char *match[])
 {
        char fullcmd[80], matchstr[80];
        struct agi_command *e;
@@ -1642,7 +2333,7 @@ static int help_workhorse(int fd, char *match[])
        if (match)
                ast_join(matchstr, sizeof(matchstr), match);
 
-       ast_cli(fd, "%5.5s %20.20s   %s\n","Dead","Command","Description");
+       ast_cli(fd, "%5.5s %30.30s   %s\n","Dead","Command","Description");
        AST_RWLIST_RDLOCK(&agi_commands);
        AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
                if (!e->cmda[0])
@@ -1653,10 +2344,11 @@ 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, "%5.5s %20.20s   %s\n", e->dead ? "Yes" : "No" , fullcmd, e->summary);
+               ast_cli(fd, "%5.5s %30.30s   %s\n", e->dead ? "Yes" : "No" , fullcmd, e->summary);
        }
        AST_RWLIST_UNLOCK(&agi_commands);
-       return 0;
+
+       return CLI_SUCCESS;
 }
 
 int ast_agi_register(struct ast_module *mod, agi_command *cmd)
@@ -1685,20 +2377,20 @@ int ast_agi_unregister(struct ast_module *mod, agi_command *cmd)
        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(&agi_commands, list);
+                       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_TRAVERSE_SAFE_END;
        AST_RWLIST_UNLOCK(&agi_commands);
        if (unregistered)
                ast_verb(2, "AGI Command '%s' unregistered\n",fullcmd);
@@ -1742,8 +2434,10 @@ static agi_command *find_command(char *cmds[], int exact)
                        if (!e->cmda[y] && !exact)
                                break;
                        /* don't segfault if the next part of a command doesn't exist */
-                       if (!e->cmda[y])
+                       if (!e->cmda[y]) {
+                               AST_RWLIST_UNLOCK(&agi_commands);
                                return NULL;
+                       }
                        if (strcasecmp(e->cmda[y], cmds[y]))
                                match = 0;
                }
@@ -1751,8 +2445,10 @@ static agi_command *find_command(char *cmds[], int exact)
                   a candidate (unless we're looking for a really inexact answer  */
                if ((exact > -1) && e->cmda[y])
                        match = 0;
-               if (match)
+               if (match) {
+                       AST_RWLIST_UNLOCK(&agi_commands);
                        return e;
+               }
        }
        AST_RWLIST_UNLOCK(&agi_commands);
        return NULL;
@@ -1768,9 +2464,9 @@ static int parse_args(char *s, int *max, char *argv[])
                switch(*s) {
                case '"':
                        /* If it's escaped, put a literal quote */
-                       if (escaped) 
+                       if (escaped)
                                goto normal;
-                       else 
+                       else
                                quoted = !quoted;
                        if (quoted && whitespace) {
                                /* If we're starting a quote, coming off white space start a new word, too */
@@ -1787,7 +2483,7 @@ static int parse_args(char *s, int *max, char *argv[])
                                whitespace = 1;
                                *(cur++) = '\0';
                        } else
-                               /* Otherwise, just treat it as anything else */ 
+                               /* Otherwise, just treat it as anything else */
                                goto normal;
                        break;
                case '\\':
@@ -1826,7 +2522,15 @@ static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int
        char *argv[MAX_ARGS];
        int argc = MAX_ARGS, res;
        agi_command *c;
-
+       const char *ami_res = "Unknown Result";
+       char *ami_cmd = ast_strdupa(buf);
+       int command_id = ast_random(), resultcode = 200;
+
+       manager_event(EVENT_FLAG_CALL, "AGIExec",
+                       "SubEvent: Start\r\n"
+                       "Channel: %s\r\n"
+                       "CommandId: %d\r\n"
+                       "Command: %s\r\n", chan->name, command_id, ami_cmd);
        parse_args(buf, &argc, argv);
        if ((c = find_command(argv, 0)) && (!dead || (dead && c->dead))) {
                /* if this command wasnt registered by res_agi, be sure to usecount
@@ -1836,11 +2540,24 @@ static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int
                res = c->handler(chan, agi, argc, argv);
                if (c->mod != ast_module_info->self)
                        ast_module_unref(c->mod);
+               switch (res) {
+               case RESULT_SHOWUSAGE: ami_res = "Usage"; resultcode = 520; break;
+               case AST_PBX_KEEPALIVE: ami_res = "KeepAlive"; resultcode = 210; break;
+               case RESULT_FAILURE: ami_res = "Failure"; resultcode = -1; break;
+               case RESULT_SUCCESS: ami_res = "Success"; resultcode = 200; break;
+               }
+               manager_event(EVENT_FLAG_CALL, "AGIExec",
+                               "SubEvent: End\r\n"
+                               "Channel: %s\r\n"
+                               "CommandId: %d\r\n"
+                               "Command: %s\r\n"
+                               "ResultCode: %d\r\n"
+                               "Result: %s\r\n", chan->name, command_id, ami_cmd, resultcode, ami_res);
                switch(res) {
                case RESULT_SHOWUSAGE:
-                       ast_agi_fdprintf(agi->fd, "520-Invalid command syntax.  Proper usage follows:\n");
-                       ast_agi_fdprintf(agi->fd, c->usage);
-                       ast_agi_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 */
@@ -1852,9 +2569,23 @@ static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int
                        return -1;
                }
        } else if ((c = find_command(argv, 0))) {
-               ast_agi_fdprintf(agi->fd, "511 Command Not Permitted on a dead channel\n");
+               ast_agi_fdprintf(chan, agi->fd, "511 Command Not Permitted on a dead channel\n");
+               manager_event(EVENT_FLAG_CALL, "AGIExec",
+                               "SubEvent: End\r\n"
+                               "Channel: %s\r\n"
+                               "CommandId: %d\r\n"
+                               "Command: %s\r\n"
+                               "ResultCode: 511\r\n"
+                               "Result: Command not permitted on a dead channel\r\n", chan->name, command_id, ami_cmd);
        } else {
-               ast_agi_fdprintf(agi->fd, "510 Invalid or unknown command\n");
+               ast_agi_fdprintf(chan, agi->fd, "510 Invalid or unknown command\n");
+               manager_event(EVENT_FLAG_CALL, "AGIExec",
+                               "SubEvent: End\r\n"
+                               "Channel: %s\r\n"
+                               "CommandId: %d\r\n"
+                               "Command: %s\r\n"
+                               "ResultCode: 510\r\n"
+                               "Result: Invalid or unknown command\r\n", chan->name, command_id, ami_cmd);
        }
        return 0;
 }
@@ -1865,8 +2596,9 @@ static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi
        enum agi_result returnstatus = AGI_RESULT_SUCCESS;
        struct ast_frame *f;
        char buf[AGI_BUF_LEN];
+       char *res = NULL;
        FILE *readf;
-       /* how many times we'll retry if ast_waitfor_nandfs will return without either 
+       /* 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 = AGI_NANDFS_RETRY;
 
@@ -1883,7 +2615,8 @@ static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi
                if (needhup) {
                        needhup = 0;
                        dead = 1;
-                       kill(pid, SIGHUP);
+                       if (pid > -1)
+                               kill(pid, SIGHUP);
                }
                ms = -1;
                c = ast_waitfor_nandfds(&chan, dead ? 0 : 1, &agi->ctrl, 1, NULL, &outfd, &ms);
@@ -1900,7 +2633,7 @@ static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi
                                /* If it's voice, write it to the audio pipe */
                                if ((agi->audio > -1) && (f->frametype == AST_FRAME_VOICE)) {
                                        /* Write, ignoring errors */
-                                       write(agi->audio, f->data, f->datalen);
+                                       write(agi->audio, f->data.ptr, f->datalen);
                                }
                                ast_frfree(f);
                        }
@@ -1912,12 +2645,16 @@ static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi
                        buf[0] = '\0';
 
                        while (buflen < (len - 1)) {
-                               fgets(buf + buflen, len, readf);
-                               if (feof(readf)) 
+                               res = fgets(buf + buflen, len, readf);
+                               if (feof(readf))
                                        break;
-                               if (ferror(readf) && ((errno != EINTR) && (errno != EAGAIN))) 
+                               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));
@@ -1927,7 +2664,7 @@ static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi
                                /* Program terminated */
                                if (returnstatus && returnstatus != AST_PBX_KEEPALIVE)
                                        returnstatus = -1;
-                               ast_verb(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 */
@@ -1935,11 +2672,17 @@ static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi
                                break;
                        }
 
+                       /* Special case for inability to execute child process */
+                       if (*buf && strncasecmp(buf, "failure", 7) == 0) {
+                               returnstatus = AGI_RESULT_FAILURE;
+                               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);
+                               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)) {
@@ -1958,39 +2701,53 @@ static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi
        if (pid > -1) {
                const char *sighup = pbx_builtin_getvar_helper(chan, "AGISIGHUP");
                if (ast_strlen_zero(sighup) || !ast_false(sighup)) {
-                       if (kill(pid, SIGHUP))
+                       if (kill(pid, SIGHUP)) {
                                ast_log(LOG_WARNING, "unable to send SIGHUP to AGI process %d: %s\n", pid, strerror(errno));
+                       } else { /* Give the process a chance to die */
+                               usleep(1);
+                       }
                }
+               waitpid(pid, status, WNOHANG);
        }
        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);
-                       ast_cli(fd, " Runs Dead : %s\n", e->dead ? "Yes" : "No");
+       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";
+       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, "%s", command->usage);
+                       ast_cli(a->fd, " Runs Dead : %s\n", command->dead ? "Yes" : "No");
                } else {
-                       if (find_command(argv + 2, -1)) {
-                               return help_workhorse(fd, argv + 2);
+                       if (find_command(a->argv + e->args, -1)) {
+                               return help_workhorse(a->fd, a->argv + e->args);
                        } else {
-                               ast_join(fullcmd, sizeof(fullcmd), argv + 2);
-                               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;
 }
 
 /*! \brief Convert string to use HTML escaped characters
@@ -2024,49 +2781,41 @@ static void write_html_escaped(FILE *htmlfile, char *str)
        return;
 }
 
-static int handle_agidumphtml(int fd, int argc, char *argv[])
+static int write_htmldump(char *filename)
 {
-       struct agi_command *e;
+       struct agi_command *command;
        char fullcmd[80];
        FILE *htmlfile;
 
-       if ((argc < 3))
-               return RESULT_SHOWUSAGE;
-
-       if (!(htmlfile = fopen(argv[2], "wt"))) {
-               ast_cli(fd, "Could not create file '%s'\n", argv[2]);
-               return RESULT_SHOWUSAGE;
-       }
+       if (!(htmlfile = fopen(filename, "wt")))
+               return -1;
 
        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");
 
        AST_RWLIST_RDLOCK(&agi_commands);
-       AST_RWLIST_TRAVERSE(&agi_commands, e, list) {
+       AST_RWLIST_TRAVERSE(&agi_commands, command, list) {
                char *stringp, *tempstr;
-               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></TH></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\">");
                write_html_escaped(htmlfile, tempstr);
                fprintf(htmlfile, "</TD></TR>\n");
-
-               
                fprintf(htmlfile, "<TR><TD ALIGN=\"CENTER\">\n");
+
                while ((tempstr = strsep(&stringp, "\n")) != NULL) {
                        write_html_escaped(htmlfile, tempstr);
                        fprintf(htmlfile, "<BR>\n");
@@ -2077,14 +2826,60 @@ static int handle_agidumphtml(int fd, int argc, char *argv[])
        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;
+       return 0;
+}
+
+static char *handle_cli_agi_dumphtml_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       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 (write_htmldump(a->argv[2]) < 0) {
+               ast_cli(a->fd, "Could not create file '%s'\n", a->argv[2]);
+               return CLI_SHOWUSAGE;
+       }
+       ast_cli(a->fd, "AGI HTML commands dumped to: %s\n", a->argv[2]);
+       return CLI_SUCCESS;
+}
+
+static char *handle_cli_agi_dump_html(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "agi dump html";
+               e->usage =
+                       "Usage: agi dump html <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 (write_htmldump(a->argv[e->args]) < 0) {
+               ast_cli(a->fd, "Could not create file '%s'\n", a->argv[e->args]);
+               return CLI_SHOWUSAGE;
+       }
+       ast_cli(a->fd, "AGI HTML commands dumped to: %s\n", a->argv[e->args]);
+       return CLI_SUCCESS;
 }
 
 static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced, int dead)
 {
        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,
@@ -2097,42 +2892,42 @@ static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced, int
                return -1;
        }
        if (dead)
-               ast_log(LOG_NOTICE, "Hungup channel detected, running agi in dead mode.");
+               ast_debug(3, "Hungup channel detected, running agi in dead mode.\n");
        ast_copy_string(buf, data, sizeof(buf));
        memset(&agi, 0, sizeof(agi));
        AST_STANDARD_APP_ARGS(args, tmp);
        args.argv[args.argc] = NULL;
-
-       u = ast_module_user_add(chan);
 #if 0
         /* Answer if need be */
        if (chan->_state != AST_STATE_UP) {
-               if (ast_answer(chan)) {
-                       LOCAL_USER_REMOVE(u);
+               if (ast_answer(chan))
                        return -1;
-               }
        }
 #endif
-       res = launch_script(args.argv[0], args.argv, fds, enhanced ? &efd : NULL, &pid);
-       if (res == AGI_RESULT_SUCCESS) {
+       res = launch_script(chan, args.argv[0], args.argv, fds, enhanced ? &efd : NULL, &pid);
+       /* Async AGI do not require run_agi(), so just proceed if normal AGI
+          or Fast AGI are setup with success. */
+       if (res == AGI_RESULT_SUCCESS || res == AGI_RESULT_SUCCESS_FAST) {
                int status = 0;
                agi.fd = fds[1];
                agi.ctrl = fds[0];
                agi.audio = efd;
+               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 && status)
+               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_module_user_remove(u);
+       ast_safe_fork_cleanup();
 
        switch (res) {
        case AGI_RESULT_SUCCESS:
+       case AGI_RESULT_SUCCESS_FAST:
+       case AGI_RESULT_SUCCESS_ASYNC:
                pbx_builtin_setvar_helper(chan, "AGISTATUS", "SUCCESS");
                break;
        case AGI_RESULT_FAILURE:
@@ -2162,7 +2957,7 @@ static int eagi_exec(struct ast_channel *chan, void *data)
        int readformat, res;
 
        if (ast_check_hangup(chan)) {
-               ast_log(LOG_ERROR, "If you want to run AGI on hungup channels you should use DeadAGI!\n");
+               ast_log(LOG_ERROR, "EAGI cannot be run on a dead/hungup channel, please use AGI.\n");
                return 0;
        }
        readformat = chan->readformat;
@@ -2181,46 +2976,26 @@ static int eagi_exec(struct ast_channel *chan, void *data)
 
 static int deadagi_exec(struct ast_channel *chan, void *data)
 {
-       ast_log(LOG_WARNING, "DeadAGI has been deprecated, please use AGI in all cases!");
+       ast_log(LOG_WARNING, "DeadAGI has been deprecated, please use AGI in all cases!\n");
        return agi_exec(chan, data);
 }
 
-static char showagi_help[] =
-"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";
-
-
-static char dumpagihtml_help[] =
-"Usage: agi dumphtml <filename>\n"
-"      Dumps the agi command list in html format to given filename\n";
+static struct ast_cli_entry cli_agi_dumphtml_deprecated = AST_CLI_DEFINE(handle_cli_agi_dumphtml_deprecated, "Dumps a list of AGI commands in HTML format");
 
 static struct ast_cli_entry cli_agi[] = {
-       { { "agi", "debug", NULL },
-       agi_do_debug, "Enable AGI debugging",
-       debug_usage },
-
-       { { "agi", "debug", "off", NULL },
-       agi_no_debug, "Disable AGI debugging",
-       no_debug_usage },
-
-       { { "agi", "show", NULL },
-       handle_showagi, "List AGI commands or specific help",
-       showagi_help },
-
-       { { "agi", "dumphtml", NULL },
-       handle_agidumphtml, "Dumps a list of agi commands in html format",
-       dumpagihtml_help },
+       AST_CLI_DEFINE(handle_cli_agi_add_cmd,   "Add AGI command to a channel in Async 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_dump_html, "Dumps a list of AGI commands in HTML format", .deprecate_cmd = &cli_agi_dumphtml_deprecated)
 };
 
 static int unload_module(void)
 {
-
        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);
+       ast_manager_unregister("AGI");
        return ast_unregister_application(app);
 }
 
@@ -2230,6 +3005,7 @@ static int load_module(void)
        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);
+       ast_manager_register2("AGI", EVENT_FLAG_CALL, action_add_agi_cmd, "Add an AGI command to execute by Async AGI", mandescr_asyncagi);
        return ast_register_application(app, agi_exec, synopsis, descrip);
 }