make datastore creation and destruction a generic API since it is not really channel...
[asterisk/asterisk.git] / res / res_agi.c
index 6fa0d7d..8cfc391 100644 (file)
@@ -20,7 +20,7 @@
  *
  * \brief AGI - the Asterisk Gateway Interface
  *
- * \author Mark Spencer <markster@digium.com> 
+ * \author Mark Spencer <markster@digium.com>
  */
 
 #include "asterisk.h"
@@ -52,7 +52,8 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/lock.h"
 #include "asterisk/strings.h"
 #include "asterisk/agi.h"
-#include "asterisk/version.h"
+#include "asterisk/manager.h"
+#include "asterisk/ast_version.h"
 #include "asterisk/speech.h"
 #include "asterisk/manager.h"
 
@@ -99,9 +100,10 @@ static int agidebug = 0;
 #define AGI_PORT 4573
 
 enum agi_result {
+       AGI_RESULT_FAILURE = -1,
        AGI_RESULT_SUCCESS,
        AGI_RESULT_SUCCESS_FAST,
-       AGI_RESULT_FAILURE,
+       AGI_RESULT_SUCCESS_ASYNC,
        AGI_RESULT_NOTFOUND,
        AGI_RESULT_HANGUP,
 };
@@ -140,6 +142,374 @@ int ast_agi_fdprintf(struct ast_channel *chan, int fd, char *fmt, ...)
        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)
@@ -230,16 +600,17 @@ static enum agi_result launch_netscript(char *agiurl, char *argv[], int *fds, in
        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;
@@ -271,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));
@@ -285,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) {
@@ -318,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];
@@ -373,7 +725,7 @@ static void setup_env(struct ast_channel *chan, char *request, int fd, int enhan
        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", ASTERISK_VERSION);
+       ast_agi_fdprintf(chan, fd, "agi_version: %s\n", ast_get_version());
 
        /* ANI/DNIS */
        ast_agi_fdprintf(chan, fd, "agi_callerid: %s\n", S_OR(chan->cid.cid_num, "unknown"));
@@ -464,24 +816,22 @@ static int handle_recvchar(struct ast_channel *chan, AGI *agi, int argc, char *a
                ast_agi_fdprintf(chan, agi->fd, "200 result=%d\n", res);
                return RESULT_SUCCESS;
        }
-       else {
-               ast_agi_fdprintf(chan, 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(chan, agi->fd, "200 result=1 (%s)\n", buf);
                ast_free(buf);
-       } else {        
+       } else {
                ast_agi_fdprintf(chan, agi->fd, "200 result=-1\n");
        }
        return RESULT_SUCCESS;
@@ -494,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)
+       if (res != RESULT_SUCCESS) {
                ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
-       else
+       } else {
                ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
+       }
        return RESULT_SUCCESS;
 }
 
@@ -514,12 +868,14 @@ 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(chan, agi->fd, "200 result=%d\n", res);
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
 }
@@ -527,36 +883,34 @@ static int handle_sendimage(struct ast_channel *chan, AGI *agi, int argc, char *
 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(chan, agi->fd, "200 result=%d\n", res);
 
        return (res >= 0) ? RESULT_SUCCESS : RESULT_FAILURE;
@@ -572,7 +926,7 @@ 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))
@@ -585,7 +939,7 @@ static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char
 
        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);
@@ -597,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 */
@@ -611,7 +965,7 @@ static int handle_streamfile(struct ast_channel *chan, AGI *agi, int argc, char
        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;
@@ -623,14 +977,14 @@ 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))) {
@@ -641,7 +995,7 @@ static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, char *
 
        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);
@@ -679,7 +1033,7 @@ static int handle_getoption(struct ast_channel *chan, AGI *agi, int argc, char *
 
 
 
-/*--- 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[])
 {
@@ -761,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;
 
@@ -772,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";
                }
        }
 
@@ -812,11 +1166,11 @@ 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);
@@ -840,7 +1194,7 @@ static int handle_setcontext(struct ast_channel *chan, AGI *agi, int argc, char
        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)
@@ -855,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)
@@ -866,7 +1220,7 @@ static int handle_setpriority(struct ast_channel *chan, AGI *agi, int argc, char
        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;
@@ -881,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 */
 
@@ -924,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 */
@@ -949,16 +1302,16 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
                                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);
@@ -971,7 +1324,7 @@ static int handle_recordfile(struct ast_channel *chan, AGI *agi, int argc, char
                        }
                        f = ast_read(chan);
                        if (!f) {
-                               ast_agi_fdprintf(chan, 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);
@@ -1026,11 +1379,11 @@ 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);
-               }               
+               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);
        }
@@ -1039,25 +1392,28 @@ 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;
+       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;
 }
@@ -1100,7 +1456,23 @@ 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;
@@ -1213,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;
@@ -1221,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]);
 
-       if (level <= option_verbose)
-               ast_verbose("%s %s: %s\n", prefix, chan->data, argv[1]);
-       
        ast_agi_fdprintf(chan, agi->fd, "200 result=1\n");
-       
+
        return RESULT_SUCCESS;
 }
 
@@ -1253,7 +1607,7 @@ 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) 
+       if (res)
                ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        else
                ast_agi_fdprintf(chan, agi->fd, "200 result=1 (%s)\n", tmp);
@@ -1302,9 +1656,9 @@ static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_c
 {
        switch (cmd) {
        case CLI_INIT:
-               e->command = "agi debug [off]";
+               e->command = "agi set debug [on|off]";
                e->usage =
-                       "Usage: agi debug [off]\n"
+                       "Usage: agi set debug [on|off]\n"
                        "       Enables/disables dumping of AGI transactions for\n"
                        "       debugging purposes.\n";
                return NULL;
@@ -1312,16 +1666,16 @@ static char *handle_cli_agi_debug(struct ast_cli_entry *e, int cmd, struct ast_c
        case CLI_GENERATE:
                return NULL;
        }
-       if (a->argc < e->args - 1 || a->argc > e->args )
+
+       if (a->argc != e->args)
                return CLI_SHOWUSAGE;
-       if (a->argc == e->args - 1) {
+
+       if (strncasecmp(a->argv[3], "off", 3) == 0) {
+               agidebug = 0;
+       } else if (strncasecmp(a->argv[3], "on", 2) == 0) {
                agidebug = 1;
        } else {
-               if (strncasecmp(a->argv[e->args - 1], "off", 3) == 0) {
-                       agidebug = 0;
-               } else {
-                       return CLI_SHOWUSAGE;
-               }
+               return CLI_SHOWUSAGE;
        }
        ast_cli(a->fd, "AGI Debugging %sabled\n", agidebug ? "En" : "Dis");
        return CLI_SUCCESS;
@@ -1350,12 +1704,12 @@ static int handle_speechcreate(struct ast_channel *chan, AGI *agi, int argc, cha
                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");
-       
+
        return RESULT_SUCCESS;
 }
 
@@ -1364,16 +1718,16 @@ static int handle_speechset(struct ast_channel *chan, AGI *agi, int argc, char *
        /* Check for minimum arguments */
         if (argc != 3)
                return RESULT_SHOWUSAGE;
-       
+
        /* 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;
 }
 
@@ -1386,7 +1740,7 @@ static int handle_speechdestroy(struct ast_channel *chan, AGI *agi, int argc, ch
        } else {
                ast_agi_fdprintf(chan, agi->fd, "200 result=0\n");
        }
-       
+
        return RESULT_SUCCESS;
 }
 
@@ -1394,17 +1748,17 @@ static int handle_speechloadgrammar(struct ast_channel *chan, AGI *agi, int argc
 {
        if (argc != 5)
                return RESULT_SHOWUSAGE;
-       
+
        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;
 }
 
@@ -1412,17 +1766,17 @@ static int handle_speechunloadgrammar(struct ast_channel *chan, AGI *agi, int ar
 {
        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;
 }
 
@@ -1430,17 +1784,17 @@ static int handle_speechactivategrammar(struct ast_channel *chan, AGI *agi, int
 {
        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;
 }
 
@@ -1448,36 +1802,36 @@ static int handle_speechdeactivategrammar(struct ast_channel *chan, AGI *agi, in
 {
        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;
 }
 
@@ -1492,47 +1846,47 @@ static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc,
        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))) {
@@ -1540,7 +1894,7 @@ static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc,
                                break;
                        }
                }
-               
+
                /* Perform timeout check */
                if ((timeout > 0) && (start > 0)) {
                        time(&current);
@@ -1551,17 +1905,17 @@ static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc,
                                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:
@@ -1572,7 +1926,7 @@ static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc,
                        }
                        /* Write audio frame data into speech engine if possible */
                        if (fr && fr->frametype == AST_FRAME_VOICE)
-                               ast_speech_write(speech, fr->data, fr->datalen);
+                               ast_speech_write(speech, fr->data.ptr, fr->datalen);
                        break;
                case AST_SPEECH_STATE_WAIT:
                        /* Cue waiting sound if not already playing */
@@ -1594,7 +1948,7 @@ static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc,
                        break;
                }
                ast_mutex_unlock(&speech->lock);
-               
+
                /* Check frame for DTMF or hangup */
                if (fr) {
                        if (fr->frametype == AST_FRAME_DTMF) {
@@ -1606,7 +1960,7 @@ static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc,
                        ast_frfree(fr);
                }
        }
-       
+
        if (!strcasecmp(reason, "speech")) {
                /* Build string containing speech results */
                 for (result = speech->results; result; result = AST_LIST_NEXT(result, list)) {
@@ -1624,10 +1978,16 @@ static int handle_speechrecognize(struct ast_channel *chan, AGI *agi, int argc,
        } 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"
@@ -1684,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"
@@ -1710,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"
@@ -1776,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";
 
@@ -1871,6 +2231,10 @@ 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";
@@ -1956,6 +2320,7 @@ static struct agi_command commands[] = {
        { { "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);
@@ -2012,7 +2377,7 @@ 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);
@@ -2069,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;
                }
@@ -2078,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;
@@ -2095,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 */
@@ -2114,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 '\\':
@@ -2157,7 +2526,7 @@ static int agi_handle_command(struct ast_channel *chan, AGI *agi, char *buf, int
        char *ami_cmd = ast_strdupa(buf);
        int command_id = ast_random(), resultcode = 200;
 
-       manager_event(EVENT_FLAG_CALL, "AGIExec", 
+       manager_event(EVENT_FLAG_CALL, "AGIExec",
                        "SubEvent: Start\r\n"
                        "Channel: %s\r\n"
                        "CommandId: %d\r\n"
@@ -2229,7 +2598,7 @@ static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi
        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;
 
@@ -2264,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);
                        }
@@ -2277,9 +2646,9 @@ static enum agi_result run_agi(struct ast_channel *chan, char *request, AGI *agi
 
                        while (buflen < (len - 1)) {
                                res = fgets(buf + buflen, len, readf);
-                               if (feof(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;
@@ -2303,6 +2672,12 @@ 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;
@@ -2326,9 +2701,13 @@ 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;
@@ -2347,7 +2726,6 @@ static char *handle_cli_agi_show(struct ast_cli_entry *e, int cmd, struct ast_cl
                        "       When called with a topic as an argument, displays usage\n"
                        "       information on the given command.  If called without a\n"
                        "       topic, it provides a list of AGI commands.\n";
-               break;
        case CLI_GENERATE:
                return NULL;
        }
@@ -2356,7 +2734,7 @@ static char *handle_cli_agi_show(struct ast_cli_entry *e, int cmd, struct ast_cl
        if (a->argc > e->args) {
                command = find_command(a->argv + e->args, 1);
                if (command) {
-                       ast_cli(a->fd, command->usage);
+                       ast_cli(a->fd, "%s", command->usage);
                        ast_cli(a->fd, " Runs Dead : %s\n", command->dead ? "Yes" : "No");
                } else {
                        if (find_command(a->argv + e->args, -1)) {
@@ -2403,30 +2781,14 @@ static void write_html_escaped(FILE *htmlfile, char *str)
        return;
 }
 
-static char *handle_cli_agi_dumphtml(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+static int write_htmldump(char *filename)
 {
        struct agi_command *command;
        char fullcmd[80];
        FILE *htmlfile;
 
-       switch (cmd) {
-       case CLI_INIT:
-               e->command = "agi dumphtml";
-               e->usage =
-                       "Usage: agi dumphtml <filename>\n"
-                       "       Dumps the AGI command list in HTML format to the given\n"
-                       "       file.\n";
-               return NULL;
-       case CLI_GENERATE:
-               return NULL;
-       }
-       if (a->argc < e->args + 1)
-               return CLI_SHOWUSAGE;
-
-       if (!(htmlfile = fopen(a->argv[2], "wt"))) {
-               ast_cli(a->fd, "Could not create file '%s'\n", a->argv[2]);
-               return CLI_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");
@@ -2435,7 +2797,7 @@ static char *handle_cli_agi_dumphtml(struct ast_cli_entry *e, int cmd, struct as
        AST_RWLIST_RDLOCK(&agi_commands);
        AST_RWLIST_TRAVERSE(&agi_commands, command, list) {
                char *stringp, *tempstr;
+
                if (!command->cmda[0])  /* end ? */
                        break;
                /* Hide commands that start with '_' */
@@ -2464,14 +2826,60 @@ static char *handle_cli_agi_dumphtml(struct ast_cli_entry *e, int cmd, struct as
        AST_RWLIST_UNLOCK(&agi_commands);
        fprintf(htmlfile, "</TABLE>\n</BODY>\n</HTML>\n");
        fclose(htmlfile);
+       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,
@@ -2484,23 +2892,21 @@ 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.\n");
+               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)) {
-                       ast_module_user_remove(u);
+               if (ast_answer(chan))
                        return -1;
-               }
        }
 #endif
-       res = launch_script(args.argv[0], args.argv, fds, enhanced ? &efd : NULL, &pid);
+       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];
@@ -2515,13 +2921,13 @@ static int agi_exec_full(struct ast_channel *chan, void *data, int enhanced, int
                        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:
@@ -2551,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;
@@ -2574,10 +2980,13 @@ static int deadagi_exec(struct ast_channel *chan, void *data)
        return agi_exec(chan, data);
 }
 
+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[] = {
-       AST_CLI_DEFINE(handle_cli_agi_debug,    "Enable/Disable AGI debugging"),
-       AST_CLI_DEFINE(handle_cli_agi_show,     "List AGI commands or specific help"),
-       AST_CLI_DEFINE(handle_cli_agi_dumphtml, "Dumps a list of AGI commands in HTML format")
+       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)
@@ -2586,6 +2995,7 @@ static int unload_module(void)
        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);
 }
 
@@ -2595,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);
 }