Modules: Additional improvements to CLI completion.
[asterisk/asterisk.git] / main / cli.c
index 6474f3e..0896181 100644 (file)
 
 #include "asterisk.h"
 
-ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
-
 #include "asterisk/_private.h"
 #include "asterisk/paths.h"    /* use ast_config_AST_MODULE_DIR */
-#include <sys/signal.h>
 #include <signal.h>
 #include <ctype.h>
 #include <regex.h>
 #include <pwd.h>
 #include <grp.h>
-#include <editline/readline.h>
 
 #include "asterisk/cli.h"
 #include "asterisk/linkedlists.h"
@@ -63,6 +59,8 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/bridge.h"
 #include "asterisk/stasis_channels.h"
 #include "asterisk/stasis_bridges.h"
+#include "asterisk/vector.h"
+#include "asterisk/stream.h"
 
 /*!
  * \brief List of restrictions per user.
@@ -106,11 +104,12 @@ AST_RWLIST_HEAD(module_level_list, module_level);
 
 /*! list of module names and their debug levels */
 static struct module_level_list debug_modules = AST_RWLIST_HEAD_INIT_VALUE;
-/*! list of module names and their verbose levels */
-static struct module_level_list verbose_modules = AST_RWLIST_HEAD_INIT_VALUE;
 
 AST_THREADSTORAGE(ast_cli_buf);
 
+AST_RWLOCK_DEFINE_STATIC(shutdown_commands_lock);
+static AST_VECTOR(, struct ast_cli_entry *) shutdown_commands;
+
 /*! \brief Initial buffer size for resulting strings in ast_cli() */
 #define AST_CLI_INITLEN   256
 
@@ -151,19 +150,7 @@ unsigned int ast_debug_get_by_module(const char *module)
 
 unsigned int ast_verbose_get_by_module(const char *module)
 {
-       struct module_level *ml;
-       unsigned int res = 0;
-
-       AST_RWLIST_RDLOCK(&verbose_modules);
-       AST_LIST_TRAVERSE(&verbose_modules, ml, entry) {
-               if (!strcasecmp(ml->module, module)) {
-                       res = ml->level;
-                       break;
-               }
-       }
-       AST_RWLIST_UNLOCK(&verbose_modules);
-
-       return res;
+       return 0;
 }
 
 /*! \internal
@@ -236,28 +223,6 @@ static int cli_has_permissions(int uid, int gid, const char *command)
 
 static AST_RWLIST_HEAD_STATIC(helpers, ast_cli_entry);
 
-static char *complete_fn(const char *word, int state)
-{
-       char *c, *d;
-       char filename[PATH_MAX];
-
-       if (word[0] == '/')
-               ast_copy_string(filename, word, sizeof(filename));
-       else
-               snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
-
-       c = d = filename_completion_function(filename, state);
-
-       if (c && word[0] != '/')
-               c += (strlen(ast_config_AST_MODULE_DIR) + 1);
-       if (c)
-               c = ast_strdup(c);
-
-       free(d);
-
-       return c;
-}
-
 static char *handle_load(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        /* "module load <mod>" */
@@ -270,12 +235,14 @@ static char *handle_load(struct ast_cli_entry *e, int cmd, struct ast_cli_args *
                return NULL;
 
        case CLI_GENERATE:
-               if (a->pos != e->args)
+               if (a->pos != e->args) {
                        return NULL;
-               return complete_fn(a->word, a->n);
+               }
+               return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_LOAD);
        }
-       if (a->argc != e->args + 1)
+       if (a->argc != e->args + 1) {
                return CLI_SHOWUSAGE;
+       }
        if (ast_load_resource(a->argv[e->args])) {
                ast_cli(a->fd, "Unable to load module %s\n", a->argv[e->args]);
                return CLI_FAILURE;
@@ -298,7 +265,7 @@ static char *handle_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args
                return NULL;
 
        case CLI_GENERATE:
-               return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 1);
+               return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_RELOAD);
        }
        if (a->argc == e->args) {
                ast_module_reload(NULL);
@@ -357,14 +324,19 @@ static char *handle_core_reload(struct ast_cli_entry *e, int cmd, struct ast_cli
 
        return CLI_SUCCESS;
 }
+
 /*!
- * \brief Find the debug or verbose file setting
- * \arg debug 1 for debug, 0 for verbose
+ * \brief Find the module level setting
+ *
+ * \param module Module name to look for.
+ * \param mll List to search.
+ *
+ * \retval level struct found on success.
+ * \retval NULL not found.
  */
-static struct module_level *find_module_level(const char *module, unsigned int debug)
+static struct module_level *find_module_level(const char *module, struct module_level_list *mll)
 {
        struct module_level *ml;
-       struct module_level_list *mll = debug ? &debug_modules : &verbose_modules;
 
        AST_LIST_TRAVERSE(mll, ml, entry) {
                if (!strcasecmp(ml->module, module))
@@ -379,7 +351,7 @@ static char *complete_number(const char *partial, unsigned int min, unsigned int
        int i, count = 0;
        unsigned int prospective[2];
        unsigned int part = strtoul(partial, NULL, 10);
-       char next[12];
+       char next[13];
 
        if (part < min || part > max) {
                return NULL;
@@ -414,52 +386,69 @@ static char *complete_number(const char *partial, unsigned int min, unsigned int
        return NULL;
 }
 
-static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+static void status_debug_verbose(struct ast_cli_args *a, const char *what, int old_val, int cur_val)
+{
+       char was_buf[30];
+       const char *was;
+
+       if (old_val) {
+               snprintf(was_buf, sizeof(was_buf), "%d", old_val);
+               was = was_buf;
+       } else {
+               was = "OFF";
+       }
+
+       if (old_val == cur_val) {
+               ast_cli(a->fd, "%s is still %s.\n", what, was);
+       } else {
+               char now_buf[30];
+               const char *now;
+
+               if (cur_val) {
+                       snprintf(now_buf, sizeof(now_buf), "%d", cur_val);
+                       now = now_buf;
+               } else {
+                       now = "OFF";
+               }
+
+               ast_cli(a->fd, "%s was %s and is now %s.\n", what, was, now);
+       }
+}
+
+static char *handle_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        int oldval;
        int newlevel;
-       unsigned int is_debug;
        int atleast = 0;
-       int fd = a->fd;
-       int argc = a->argc;
-       const char * const *argv = a->argv;
        const char *argv3 = a->argv ? S_OR(a->argv[3], "") : "";
-       int *dst;
-       char *what;
-       struct module_level_list *mll;
        struct module_level *ml;
 
        switch (cmd) {
        case CLI_INIT:
-               e->command = "core set {debug|verbose}";
+               e->command = "core set debug";
                e->usage =
-#if !defined(LOW_MEMORY)
-                       "Usage: core set {debug|verbose} [atleast] <level> [module]\n"
-#else
-                       "Usage: core set {debug|verbose} [atleast] <level>\n"
-#endif
-                       "       core set {debug|verbose} off\n"
-#if !defined(LOW_MEMORY)
-                       "       Sets level of debug or verbose messages to be displayed or\n"
+                       "Usage: core set debug [atleast] <level> [module]\n"
+                       "       core set debug off\n"
+                       "\n"
+                       "       Sets level of debug messages to be displayed or\n"
                        "       sets a module name to display debug messages from.\n"
-#else
-                       "       Sets level of debug or verbose messages to be displayed.\n"
-#endif
-                       "       0 or off means no messages should be displayed.\n"
-                       "       Equivalent to -d[d[...]] or -v[v[v...]] on startup\n";
+                       "       0 or off means no messages should be displayed.\n"
+                       "       Equivalent to -d[d[...]] on startup\n";
                return NULL;
 
        case CLI_GENERATE:
-               if (a->pos == 3 || (a->pos == 4 && !strcasecmp(a->argv[3], "atleast"))) {
+               if (!strcasecmp(argv3, "atleast")) {
+                       atleast = 1;
+               }
+               if (a->pos == 3 || (a->pos == 4 && atleast)) {
                        const char *pos = a->pos == 3 ? argv3 : S_OR(a->argv[4], "");
                        int numbermatch = (ast_strlen_zero(pos) || strchr("123456789", pos[0])) ? 0 : 21;
+
                        if (a->n < 21 && numbermatch == 0) {
                                return complete_number(pos, 0, 0x7fffffff, a->n);
                        } else if (pos[0] == '0') {
                                if (a->n == 0) {
                                        return ast_strdup("0");
-                               } else {
-                                       return NULL;
                                }
                        } else if (a->n == (21 - numbermatch)) {
                                if (a->pos == 3 && !strncasecmp(argv3, "off", strlen(argv3))) {
@@ -470,10 +459,9 @@ static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_arg
                        } else if (a->n == (22 - numbermatch) && a->pos == 3 && ast_strlen_zero(argv3)) {
                                return ast_strdup("atleast");
                        }
-#if !defined(LOW_MEMORY)
-               } else if (a->pos == 4 || (a->pos == 5 && !strcasecmp(argv3, "atleast"))) {
-                       return ast_complete_source_filename(a->pos == 4 ? S_OR(a->argv[4], "") : S_OR(a->argv[5], ""), a->n);
-#endif
+               } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off") && strcasecmp(argv3, "channel"))
+                       || (a->pos == 5 && atleast)) {
+                       return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_RUNNING);
                }
                return NULL;
        }
@@ -481,117 +469,200 @@ static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_arg
         * we are guaranteed to be called with argc >= e->args;
         */
 
-       if (argc <= e->args)
+       if (a->argc <= e->args) {
                return CLI_SHOWUSAGE;
-       if (!strcasecmp(argv[e->args - 1], "debug")) {
-               dst = &option_debug;
-               oldval = option_debug;
-               what = "Core debug";
-               is_debug = 1;
-       } else {
-               dst = &option_verbose;
-               oldval = option_verbose;
-               what = "Verbosity";
-               is_debug = 0;
        }
-       if (argc == e->args + 1 && !strcasecmp(argv[e->args], "off")) {
+
+       if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args], "off")) {
                newlevel = 0;
+       } else {
+               if (!strcasecmp(a->argv[e->args], "atleast")) {
+                       atleast = 1;
+               }
+               if (a->argc != e->args + atleast + 1 && a->argc != e->args + atleast + 2) {
+                       return CLI_SHOWUSAGE;
+               }
+               if (sscanf(a->argv[e->args + atleast], "%30d", &newlevel) != 1) {
+                       return CLI_SHOWUSAGE;
+               }
 
-               mll = is_debug ? &debug_modules : &verbose_modules;
+               if (a->argc == e->args + atleast + 2) {
+                       /* We have specified a module name. */
+                       char *mod = ast_strdupa(a->argv[e->args + atleast + 1]);
+                       int mod_len = strlen(mod);
 
-               AST_RWLIST_WRLOCK(mll);
-               while ((ml = AST_RWLIST_REMOVE_HEAD(mll, entry))) {
-                       ast_free(ml);
-               }
-               ast_clear_flag(&ast_options, is_debug ? AST_OPT_FLAG_DEBUG_MODULE : AST_OPT_FLAG_VERBOSE_MODULE);
-               AST_RWLIST_UNLOCK(mll);
+                       if (3 < mod_len && !strcasecmp(mod + mod_len - 3, ".so")) {
+                               mod[mod_len - 3] = '\0';
+                       }
 
-               goto done;
+                       AST_RWLIST_WRLOCK(&debug_modules);
+
+                       ml = find_module_level(mod, &debug_modules);
+                       if (!newlevel) {
+                               if (!ml) {
+                                       /* Specified off for a nonexistent entry. */
+                                       AST_RWLIST_UNLOCK(&debug_modules);
+                                       ast_cli(a->fd, "Core debug is still 0 for '%s'.\n", mod);
+                                       return CLI_SUCCESS;
+                               }
+                               AST_RWLIST_REMOVE(&debug_modules, ml, entry);
+                               if (AST_RWLIST_EMPTY(&debug_modules)) {
+                                       ast_clear_flag(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
+                               }
+                               AST_RWLIST_UNLOCK(&debug_modules);
+                               ast_cli(a->fd, "Core debug was %u and has been set to 0 for '%s'.\n",
+                                       ml->level, mod);
+                               ast_free(ml);
+                               return CLI_SUCCESS;
+                       }
+
+                       if (ml) {
+                               if ((atleast && newlevel < ml->level) || ml->level == newlevel) {
+                                       ast_cli(a->fd, "Core debug is still %u for '%s'.\n", ml->level, mod);
+                                       AST_RWLIST_UNLOCK(&debug_modules);
+                                       return CLI_SUCCESS;
+                               }
+                               oldval = ml->level;
+                               ml->level = newlevel;
+                       } else {
+                               ml = ast_calloc(1, sizeof(*ml) + strlen(mod) + 1);
+                               if (!ml) {
+                                       AST_RWLIST_UNLOCK(&debug_modules);
+                                       return CLI_FAILURE;
+                               }
+                               oldval = ml->level;
+                               ml->level = newlevel;
+                               strcpy(ml->module, mod);
+                               AST_RWLIST_INSERT_TAIL(&debug_modules, ml, entry);
+                       }
+                       ast_set_flag(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
+
+                       ast_cli(a->fd, "Core debug was %d and has been set to %u for '%s'.\n",
+                               oldval, ml->level, ml->module);
+
+                       AST_RWLIST_UNLOCK(&debug_modules);
+
+                       return CLI_SUCCESS;
+               }
        }
-       if (!strcasecmp(argv[e->args], "atleast"))
-               atleast = 1;
-       if (argc != e->args + atleast + 1 && argc != e->args + atleast + 2)
-               return CLI_SHOWUSAGE;
-       if (sscanf(argv[e->args + atleast], "%30d", &newlevel) != 1)
-               return CLI_SHOWUSAGE;
-       if (argc == e->args + atleast + 2) {
-               /* We have specified a module name. */
-               char *mod = ast_strdupa(argv[e->args + atleast + 1]);
 
-               if ((strlen(mod) > 3) && !strcasecmp(mod + strlen(mod) - 3, ".so")) {
-                       mod[strlen(mod) - 3] = '\0';
+       /* Update global debug level */
+       if (!newlevel) {
+               /* Specified level was 0 or off. */
+               AST_RWLIST_WRLOCK(&debug_modules);
+               while ((ml = AST_RWLIST_REMOVE_HEAD(&debug_modules, entry))) {
+                       ast_free(ml);
                }
+               ast_clear_flag(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
+               AST_RWLIST_UNLOCK(&debug_modules);
+       }
+       oldval = option_debug;
+       if (!atleast || newlevel > option_debug) {
+               option_debug = newlevel;
+       }
 
-               mll = is_debug ? &debug_modules : &verbose_modules;
+       /* Report debug level status */
+       status_debug_verbose(a, "Core debug", oldval, option_debug);
 
-               AST_RWLIST_WRLOCK(mll);
+       return CLI_SUCCESS;
+}
 
-               ml = find_module_level(mod, is_debug);
-               if (!newlevel) {
-                       if (!ml) {
-                               /* Specified off for a nonexistent entry. */
-                               AST_RWLIST_UNLOCK(mll);
-                               return CLI_SUCCESS;
-                       }
-                       AST_RWLIST_REMOVE(mll, ml, entry);
-                       if (AST_RWLIST_EMPTY(mll))
-                               ast_clear_flag(&ast_options, is_debug ? AST_OPT_FLAG_DEBUG_MODULE : AST_OPT_FLAG_VERBOSE_MODULE);
-                       AST_RWLIST_UNLOCK(mll);
-                       ast_cli(fd, "%s was %d and has been set to 0 for '%s'\n", what, ml->level, mod);
-                       ast_free(ml);
-                       return CLI_SUCCESS;
+static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       int oldval;
+       int newlevel;
+       int atleast = 0;
+       int silent = 0;
+       const char *argv3 = a->argv ? S_OR(a->argv[3], "") : "";
+
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "core set verbose";
+               e->usage =
+                       "Usage: core set verbose [atleast] <level> [silent]\n"
+                       "       core set verbose off\n"
+                       "\n"
+                       "       Sets level of verbose messages to be displayed.\n"
+                       "       0 or off means no verbose messages should be displayed.\n"
+                       "       The silent option means the command does not report what\n"
+                       "       happened to the verbose level.\n"
+                       "       Equivalent to -v[v[...]] on startup\n";
+               return NULL;
+
+       case CLI_GENERATE:
+               if (!strcasecmp(argv3, "atleast")) {
+                       atleast = 1;
                }
+               if (a->pos == 3 || (a->pos == 4 && atleast)) {
+                       const char *pos = a->pos == 3 ? argv3 : S_OR(a->argv[4], "");
+                       int numbermatch = (ast_strlen_zero(pos) || strchr("123456789", pos[0])) ? 0 : 21;
 
-               if (ml) {
-                       if ((atleast && newlevel < ml->level) || ml->level == newlevel) {
-                               ast_cli(fd, "%s is %d for '%s'\n", what, ml->level, mod);
-                               AST_RWLIST_UNLOCK(mll);
-                               return CLI_SUCCESS;
+                       if (a->n < 21 && numbermatch == 0) {
+                               return complete_number(pos, 0, 0x7fffffff, a->n);
+                       } else if (pos[0] == '0') {
+                               if (a->n == 0) {
+                                       return ast_strdup("0");
+                               }
+                       } else if (a->n == (21 - numbermatch)) {
+                               if (a->pos == 3 && !strncasecmp(argv3, "off", strlen(argv3))) {
+                                       return ast_strdup("off");
+                               } else if (a->pos == 3 && !strncasecmp(argv3, "atleast", strlen(argv3))) {
+                                       return ast_strdup("atleast");
+                               }
+                       } else if (a->n == (22 - numbermatch) && a->pos == 3 && ast_strlen_zero(argv3)) {
+                               return ast_strdup("atleast");
                        }
-                       oldval = ml->level;
-                       ml->level = newlevel;
-               } else {
-                       ml = ast_calloc(1, sizeof(*ml) + strlen(mod) + 1);
-                       if (!ml) {
-                               AST_RWLIST_UNLOCK(mll);
-                               return CLI_FAILURE;
+               } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off"))
+                       || (a->pos == 5 && atleast)) {
+                       const char *pos = S_OR(a->argv[a->pos], "");
+
+                       if (a->n == 0 && !strncasecmp(pos, "silent", strlen(pos))) {
+                               return ast_strdup("silent");
                        }
-                       oldval = ml->level;
-                       ml->level = newlevel;
-                       strcpy(ml->module, mod);
-                       AST_RWLIST_INSERT_TAIL(mll, ml, entry);
                }
+               return NULL;
+       }
+       /* all the above return, so we proceed with the handler.
+        * we are guaranteed to be called with argc >= e->args;
+        */
 
-               ast_set_flag(&ast_options, is_debug ? AST_OPT_FLAG_DEBUG_MODULE : AST_OPT_FLAG_VERBOSE_MODULE);
+       if (a->argc <= e->args) {
+               return CLI_SHOWUSAGE;
+       }
 
-               AST_RWLIST_UNLOCK(mll);
+       if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args], "off")) {
+               newlevel = 0;
+       } else {
+               if (!strcasecmp(a->argv[e->args], "atleast")) {
+                       atleast = 1;
+               }
+               if (a->argc == e->args + atleast + 2
+                       && !strcasecmp(a->argv[e->args + atleast + 1], "silent")) {
+                       silent = 1;
+               }
+               if (a->argc != e->args + atleast + silent + 1) {
+                       return CLI_SHOWUSAGE;
+               }
+               if (sscanf(a->argv[e->args + atleast], "%30d", &newlevel) != 1) {
+                       return CLI_SHOWUSAGE;
+               }
+       }
 
-               ast_cli(fd, "%s was %d and has been set to %d for '%s'\n", what, oldval, ml->level, ml->module);
+       /* Update verbose level */
+       oldval = ast_verb_console_get();
+       if (!atleast || newlevel > oldval) {
+               ast_verb_console_set(newlevel);
+       } else {
+               newlevel = oldval;
+       }
 
+       if (silent) {
+               /* Be silent after setting the level. */
                return CLI_SUCCESS;
-       } else if (!newlevel) {
-               /* Specified level as 0 instead of off. */
-               mll = is_debug ? &debug_modules : &verbose_modules;
-
-               AST_RWLIST_WRLOCK(mll);
-               while ((ml = AST_RWLIST_REMOVE_HEAD(mll, entry))) {
-                       ast_free(ml);
-               }
-               ast_clear_flag(&ast_options, is_debug ? AST_OPT_FLAG_DEBUG_MODULE : AST_OPT_FLAG_VERBOSE_MODULE);
-               AST_RWLIST_UNLOCK(mll);
        }
 
-done:
-       if (!atleast || newlevel > *dst)
-               *dst = newlevel;
-       if (oldval > 0 && *dst == 0)
-               ast_cli(fd, "%s is now OFF\n", what);
-       else if (*dst > 0) {
-               if (oldval == *dst)
-                       ast_cli(fd, "%s is at least %d\n", what, *dst);
-               else
-                       ast_cli(fd, "%s was %d and is now %d\n", what, oldval, *dst);
-       }
+       /* Report verbose level status */
+       status_debug_verbose(a, "Console verbose", oldval, newlevel);
 
        return CLI_SUCCESS;
 }
@@ -641,7 +712,7 @@ static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args
                return NULL;
 
        case CLI_GENERATE:
-               return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
+               return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_UNLOAD);
        }
        if (a->argc < e->args + 1)
                return CLI_SHOWUSAGE;
@@ -670,17 +741,20 @@ static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args
        return CLI_SUCCESS;
 }
 
-#define MODLIST_FORMAT  "%-30s %-40.40s %-10d %s\n"
-#define MODLIST_FORMAT2 "%-30s %-40.40s %-10s %s\n"
+#define MODLIST_FORMAT  "%-30s %-40.40s %-10d %-11s %13s\n"
+#define MODLIST_FORMAT2 "%-30s %-40.40s %-10s %-11s %13s\n"
 
 AST_MUTEX_DEFINE_STATIC(climodentrylock);
 static int climodentryfd = -1;
 
-static int modlist_modentry(const char *module, const char *description, int usecnt, const char *status, const char *like)
+static int modlist_modentry(const char *module, const char *description,
+               int usecnt, const char *status, const char *like,
+               enum ast_module_support_level support_level)
 {
        /* Comparing the like with the module */
        if (strcasestr(module, like) ) {
-               ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt, status);
+               ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt,
+                               status, ast_module_support_level_to_string(support_level));
                return 1;
        }
        return 0;
@@ -697,44 +771,46 @@ static void print_uptimestr(int fd, struct timeval timeval, const char *prefix,
 #define DAY (HOUR*24)
 #define WEEK (DAY*7)
 #define YEAR (DAY*365)
-#define NEEDCOMMA(x) ((x)? ",": "")    /* define if we need a comma */
+#define NEEDCOMMA(x) ((x) ? ", " : "") /* define if we need a comma */
        if (timeval.tv_sec < 0) /* invalid, nothing to show */
                return;
 
        if (printsec)  {        /* plain seconds output */
-               ast_cli(fd, "%s: %lu\n", prefix, (u_long)timeval.tv_sec);
+               ast_cli(fd, "%s%lu\n", prefix, (u_long)timeval.tv_sec);
                return;
        }
        out = ast_str_alloca(256);
        if (timeval.tv_sec > YEAR) {
                x = (timeval.tv_sec / YEAR);
                timeval.tv_sec -= (x * YEAR);
-               ast_str_append(&out, 0, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
+               ast_str_append(&out, 0, "%d year%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
        }
        if (timeval.tv_sec > WEEK) {
                x = (timeval.tv_sec / WEEK);
                timeval.tv_sec -= (x * WEEK);
-               ast_str_append(&out, 0, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
+               ast_str_append(&out, 0, "%d week%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
        }
        if (timeval.tv_sec > DAY) {
                x = (timeval.tv_sec / DAY);
                timeval.tv_sec -= (x * DAY);
-               ast_str_append(&out, 0, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
+               ast_str_append(&out, 0, "%d day%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
        }
        if (timeval.tv_sec > HOUR) {
                x = (timeval.tv_sec / HOUR);
                timeval.tv_sec -= (x * HOUR);
-               ast_str_append(&out, 0, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
+               ast_str_append(&out, 0, "%d hour%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
        }
        if (timeval.tv_sec > MINUTE) {
                x = (timeval.tv_sec / MINUTE);
                timeval.tv_sec -= (x * MINUTE);
-               ast_str_append(&out, 0, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
+               ast_str_append(&out, 0, "%d minute%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
        }
        x = timeval.tv_sec;
-       if (x > 0 || ast_str_strlen(out) == 0)  /* if there is nothing, print 0 seconds */
-               ast_str_append(&out, 0, "%d second%s ", x, ESS(x));
-       ast_cli(fd, "%s: %s\n", prefix, ast_str_buffer(out));
+       if (x > 0 || ast_str_strlen(out) == 0) {
+               /* if there is nothing, print 0 seconds */
+               ast_str_append(&out, 0, "%d second%s", x, ESS(x));
+       }
+       ast_cli(fd, "%s%s\n", prefix, ast_str_buffer(out));
 }
 
 static struct ast_cli_entry *cli_next(struct ast_cli_entry *e)
@@ -770,10 +846,12 @@ static char * handle_showuptime(struct ast_cli_entry *e, int cmd, struct ast_cli
                printsec = 0;
        else
                return CLI_SHOWUSAGE;
-       if (ast_startuptime.tv_sec)
-               print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
-       if (ast_lastreloadtime.tv_sec)
-               print_uptimestr(a->fd, ast_tvsub(curtime, ast_lastreloadtime), "Last reload", printsec);
+       if (ast_startuptime.tv_sec) {
+               print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime: ", printsec);
+       }
+       if (ast_lastreloadtime.tv_sec) {
+               print_uptimestr(a->fd, ast_tvsub(curtime, ast_lastreloadtime), "Last reload: ", printsec);
+       }
        return CLI_SUCCESS;
 }
 
@@ -790,10 +868,11 @@ static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_arg
                return NULL;
 
        case CLI_GENERATE:
-               if (a->pos == e->args)
-                       return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
-               else
+               if (a->pos == e->args) {
+                       return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_LOADED);
+               } else {
                        return NULL;
+               }
        }
        /* all the above return, so we proceed with the handler.
         * we are guaranteed to have argc >= e->args
@@ -807,7 +886,7 @@ static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_arg
 
        ast_mutex_lock(&climodentrylock);
        climodentryfd = a->fd; /* global, protected by climodentrylock */
-       ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count", "Status");
+       ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count", "Status", "Support Level");
        ast_cli(a->fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
        climodentryfd = -1;
        ast_mutex_unlock(&climodentrylock);
@@ -818,6 +897,7 @@ static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_arg
 
 static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
+       static const char * const completions[] = { "seconds", NULL };
        struct timeval curtime = ast_tvnow();
        int showuptime, printsec;
 
@@ -825,7 +905,7 @@ static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_a
        case CLI_INIT:
                e->command = "core show calls [uptime]";
                e->usage =
-                       "Usage: core show calls [uptime] [seconds]\n"
+                       "Usage: core show calls [uptime [seconds]]\n"
                        "       Lists number of currently active calls and total number of calls\n"
                        "       processed through PBX since last restart. If 'uptime' is specified\n"
                        "       the system uptime is also displayed. If 'seconds' is specified in\n"
@@ -835,7 +915,7 @@ static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_a
        case CLI_GENERATE:
                if (a->pos != e->args)
                        return NULL;
-               return a->n == 0  ? ast_strdup("seconds") : NULL;
+               return ast_cli_complete(a->word, completions, a->n);
        }
 
        /* regular handler */
@@ -854,10 +934,10 @@ static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_a
        } else
                return CLI_SHOWUSAGE;
 
-       if (option_maxcalls) {
+       if (ast_option_maxcalls) {
                ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
-                  ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
-                  ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
+                  ast_active_calls(), ast_option_maxcalls, ESS(ast_active_calls()),
+                  ((double)ast_active_calls() / (double)ast_option_maxcalls) * 100.0);
        } else {
                ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
        }
@@ -865,7 +945,7 @@ static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_a
        ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
 
        if (ast_startuptime.tv_sec && showuptime) {
-               print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
+               print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime: ", printsec);
        }
 
        return RESULT_SUCCESS;
@@ -915,7 +995,7 @@ static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                return CLI_SHOWUSAGE;
 
 
-       if (!(channels = stasis_cache_dump(ast_channel_topic_all_cached_by_name(), ast_channel_snapshot_type()))) {
+       if (!(channels = stasis_cache_dump(ast_channel_cache_by_name(), ast_channel_snapshot_type()))) {
                ast_cli(a->fd, "Failed to retrieve cached channels\n");
                return CLI_SUCCESS;
        }
@@ -931,7 +1011,7 @@ static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
        it_chans = ao2_iterator_init(channels, 0);
        for (; (msg = ao2_iterator_next(&it_chans)); ao2_ref(msg, -1)) {
                struct ast_channel_snapshot *cs = stasis_message_data(msg);
-               char durbuf[10] = "-";
+               char durbuf[16] = "-";
 
                if (!count) {
                        if ((concise || verbose)  && !ast_tvzero(cs->creationtime)) {
@@ -969,10 +1049,12 @@ static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                                char locbuf[40] = "(None)";
                                char appdata[40] = "(None)";
 
-                               if (!cs->context && !cs->exten)
+                               if (!ast_strlen_zero(cs->context) && !ast_strlen_zero(cs->exten)) {
                                        snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", cs->exten, cs->context, cs->priority);
-                               if (cs->appl)
+                               }
+                               if (!ast_strlen_zero(cs->appl)) {
                                        snprintf(appdata, sizeof(appdata), "%s(%s)", cs->appl, S_OR(cs->data, ""));
+                               }
                                ast_cli(a->fd, FORMAT_STRING, cs->name, locbuf, ast_state2str(cs->state), appdata);
                        }
                }
@@ -982,10 +1064,10 @@ static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
        if (!concise) {
                numchans = ast_active_channels();
                ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
-               if (option_maxcalls)
+               if (ast_option_maxcalls)
                        ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
-                               ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
-                               ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
+                               ast_active_calls(), ast_option_maxcalls, ESS(ast_active_calls()),
+                               ((double)ast_active_calls() / (double)ast_option_maxcalls) * 100.0);
                else
                        ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
 
@@ -1003,7 +1085,9 @@ static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
 
 static char *handle_softhangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       struct ast_channel *c=NULL;
+       struct ast_channel *c = NULL;
+       static const char * const completions[] = { "all", NULL };
+       char *complete;
 
        switch (cmd) {
        case CLI_INIT:
@@ -1016,7 +1100,14 @@ static char *handle_softhangup(struct ast_cli_entry *e, int cmd, struct ast_cli_
                        "       will see the hangup request.\n";
                return NULL;
        case CLI_GENERATE:
-               return ast_complete_channels(a->line, a->word, a->pos, a->n, e->args);
+               if (a->pos != e->args) {
+                       return NULL;
+               }
+               complete = ast_cli_complete(a->word, completions, a->n);
+               if (!complete) {
+                       complete = ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
+               }
+               return complete;
        }
 
        if (a->argc != 4) {
@@ -1328,6 +1419,8 @@ static int channel_set_debug(void *obj, void *arg, void *data, int flags)
 static char *handle_core_set_debug_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
        struct ast_channel *c = NULL;
+       static const char * const completions_all[] = { "all", NULL };
+       static const char * const completions_off[] = { "off", NULL };
        struct channel_set_debug_args args = {
                .fd = a->fd,
        };
@@ -1340,10 +1433,15 @@ static char *handle_core_set_debug_channel(struct ast_cli_entry *e, int cmd, str
                        "       Enables/disables debugging on all or on a specific channel.\n";
                return NULL;
        case CLI_GENERATE:
-               /* XXX remember to handle the optional "off" */
-               if (a->pos != e->args)
-                       return NULL;
-               return a->n == 0 ? ast_strdup("all") : ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
+               if (a->pos == 4) {
+                       char *complete = ast_cli_complete(a->word, completions_all, a->n);
+                       if (!complete) {
+                               complete = ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
+                       }
+                       return complete;
+               } else if (a->pos == 5) {
+                       return ast_cli_complete(a->word, completions_off, a->n);
+               }
        }
 
        if (cmd == (CLI_HANDLER + 1000)) {
@@ -1411,8 +1509,7 @@ static char *handle_nodebugchan_deprecated(struct ast_cli_entry *e, int cmd, str
 
 static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
-       struct ast_channel_snapshot *snapshot;
+       struct ast_channel *chan;
        struct timeval now;
        char cdrtime[256];
        struct ast_str *obuf;/*!< Buffer for CDR variables. */
@@ -1420,6 +1517,13 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
        long elapsed_seconds=0;
        int hour=0, min=0, sec=0;
        struct ast_var_t *var;
+       struct ast_str *write_transpath = ast_str_alloca(256);
+       struct ast_str *read_transpath = ast_str_alloca(256);
+       struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
+       struct ast_bridge *bridge;
+       ast_callid callid;
+       char callid_buf[32];
+       int stream_num;
 
        switch (cmd) {
        case CLI_INIT:
@@ -1436,25 +1540,27 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                return CLI_SHOWUSAGE;
        }
 
-       now = ast_tvnow();
-
-       if (!(msg = stasis_cache_get(ast_channel_topic_all_cached_by_name(), ast_channel_snapshot_type(), a->argv[3]))) {
-               ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
-               return CLI_SUCCESS;
-       }
-       snapshot = stasis_message_data(msg);
-
        obuf = ast_str_thread_get(&ast_str_thread_global_buf, 16);
        if (!obuf) {
                return CLI_FAILURE;
        }
+
        output = ast_str_create(8192);
        if (!output) {
                return CLI_FAILURE;
        }
 
-       if (!ast_tvzero(snapshot->creationtime)) {
-               elapsed_seconds = now.tv_sec - snapshot->creationtime.tv_sec;
+       chan = ast_channel_get_by_name(a->argv[3]);
+       if (!chan) {
+               ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
+               return CLI_SUCCESS;
+       }
+
+       now = ast_tvnow();
+       ast_channel_lock(chan);
+
+       if (!ast_tvzero(ast_channel_creationtime(chan))) {
+               elapsed_seconds = now.tv_sec - ast_channel_creationtime(chan).tv_sec;
                hour = elapsed_seconds / 3600;
                min = (elapsed_seconds % 3600) / 60;
                sec = elapsed_seconds % 60;
@@ -1463,6 +1569,16 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                strcpy(cdrtime, "N/A");
        }
 
+       ast_translate_path_to_str(ast_channel_writetrans(chan), &write_transpath);
+       ast_translate_path_to_str(ast_channel_readtrans(chan), &read_transpath);
+
+       bridge = ast_channel_get_bridge(chan);
+       callid_buf[0] = '\0';
+       callid = ast_channel_callid(chan);
+       if (callid) {
+               ast_callid_strnprint(callid_buf, sizeof(callid_buf), callid);
+       }
+
        ast_str_append(&output, 0,
                " -- General --\n"
                "           Name: %s\n"
@@ -1477,7 +1593,7 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                "Eff. Connected Line ID Name: %s\n"
                "    DNID Digits: %s\n"
                "       Language: %s\n"
-               "          State: %s (%d)\n"
+               "          State: %s (%u)\n"
                "  NativeFormats: %s\n"
                "    WriteFormat: %s\n"
                "     ReadFormat: %s\n"
@@ -1495,51 +1611,83 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                "    Application: %s\n"
                "           Data: %s\n"
                " Call Identifer: %s\n",
-               snapshot->name,
-               snapshot->type,
-               snapshot->uniqueid,
-               snapshot->linkedid,
-               S_OR(snapshot->caller_number, "(N/A)"),
-               S_OR(snapshot->caller_name, "(N/A)"),
-               S_OR(snapshot->connected_number, "(N/A)"),
-               S_OR(snapshot->connected_name, "(N/A)"),
-               S_OR(snapshot->effective_number, "(N/A)"),
-               S_OR(snapshot->effective_name, "(N/A)"),
-               S_OR(snapshot->caller_dnid, "(N/A)"),
-               snapshot->language,
-               ast_state2str(snapshot->state),
-               snapshot->state,
-               snapshot->nativeformats,
-               snapshot->writeformat,
-               snapshot->readformat,
-               !ast_strlen_zero(snapshot->writetrans) ? "Yes" : "No",
-               snapshot->writetrans,
-               !ast_strlen_zero(snapshot->readtrans) ? "Yes" : "No",
-               snapshot->readtrans,
-               (long) snapshot->hanguptime.tv_sec,
+               ast_channel_name(chan),
+               ast_channel_tech(chan)->type,
+               ast_channel_uniqueid(chan),
+               ast_channel_linkedid(chan),
+               S_COR(ast_channel_caller(chan)->id.number.valid,
+                     ast_channel_caller(chan)->id.number.str, "(N/A)"),
+               S_COR(ast_channel_caller(chan)->id.name.valid,
+                     ast_channel_caller(chan)->id.name.str, "(N/A)"),
+               S_COR(ast_channel_connected(chan)->id.number.valid,
+                     ast_channel_connected(chan)->id.number.str, "(N/A)"),
+               S_COR(ast_channel_connected(chan)->id.name.valid,
+                     ast_channel_connected(chan)->id.name.str, "(N/A)"),
+               S_COR(ast_channel_connected_effective_id(chan).number.valid,
+                     ast_channel_connected_effective_id(chan).number.str, "(N/A)"),
+               S_COR(ast_channel_connected_effective_id(chan).name.valid,
+                     ast_channel_connected_effective_id(chan).name.str, "(N/A)"),
+               S_OR(ast_channel_dialed(chan)->number.str, "(N/A)"),
+               ast_channel_language(chan),
+               ast_state2str(ast_channel_state(chan)),
+               ast_channel_state(chan),
+               ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf),
+               ast_format_get_name(ast_channel_writeformat(chan)),
+               ast_format_get_name(ast_channel_readformat(chan)),
+               ast_str_strlen(write_transpath) ? "Yes" : "No",
+               ast_str_buffer(write_transpath),
+               ast_str_strlen(read_transpath) ? "Yes" : "No",
+               ast_str_buffer(read_transpath),
+               (long)ast_channel_whentohangup(chan)->tv_sec,
                cdrtime,
-               S_OR(snapshot->bridgeid, "(Not bridged)"),
-               snapshot->context,
-               snapshot->exten,
-               snapshot->priority,
-               snapshot->callgroup,
-               snapshot->pickupgroup,
-               S_OR(snapshot->appl, "(N/A)"),
-               S_OR(snapshot->data, "(Empty)"),
-               S_OR(snapshot->callid, "(None)"));
+               bridge ? bridge->uniqueid : "(Not bridged)",
+               ast_channel_context(chan),
+               ast_channel_exten(chan),
+               ast_channel_priority(chan),
+               ast_channel_callgroup(chan),
+               ast_channel_pickupgroup(chan),
+               S_OR(ast_channel_appl(chan), "(N/A)"),
+               S_OR(ast_channel_data(chan), "(Empty)"),
+               S_OR(callid_buf, "(None)")
+               );
 
        ast_str_append(&output, 0, "      Variables:\n");
 
-       AST_LIST_TRAVERSE(snapshot->channel_vars, var, entries) {
+       AST_LIST_TRAVERSE(ast_channel_varshead(chan), var, entries) {
                ast_str_append(&output, 0, "%s=%s\n", ast_var_name(var), ast_var_value(var));
        }
 
-       if (ast_cdr_serialize_variables(snapshot->name, &obuf, '=', '\n')) {
+       if (!(ast_channel_tech(chan)->properties & AST_CHAN_TP_INTERNAL)
+               && ast_cdr_serialize_variables(ast_channel_name(chan), &obuf, '=', '\n')) {
                ast_str_append(&output, 0, "  CDR Variables:\n%s\n", ast_str_buffer(obuf));
        }
 
+       ast_str_append(&output, 0, " -- Streams --\n");
+       for (stream_num = 0; stream_num < ast_stream_topology_get_count(ast_channel_get_stream_topology(chan)); stream_num++) {
+               struct ast_stream *stream = ast_stream_topology_get_stream(ast_channel_get_stream_topology(chan), stream_num);
+
+               ast_str_append(&output, 0,
+                       "Name: %s\n"
+                       "    Type: %s\n"
+                       "    State: %s\n"
+                       "    Group: %d\n"
+                       "    Formats: %s\n",
+                       ast_stream_get_name(stream),
+                       ast_codec_media_type2str(ast_stream_get_type(stream)),
+                       ast_stream_state2str(ast_stream_get_state(stream)),
+                       ast_stream_get_group(stream),
+                       ast_format_cap_get_names(ast_stream_get_formats(stream), &codec_buf)
+                       );
+       }
+
+       ast_channel_unlock(chan);
+
        ast_cli(a->fd, "%s", ast_str_buffer(output));
        ast_free(output);
+
+       ao2_cleanup(bridge);
+       ast_channel_unref(chan);
+
        return CLI_SUCCESS;
 }
 
@@ -1571,7 +1719,7 @@ char *ast_complete_channels(const char *line, const char *word, int pos, int sta
                return NULL;
        }
 
-       if (!(cached_channels = stasis_cache_dump(ast_channel_topic_all_cached(), ast_channel_snapshot_type()))) {
+       if (!(cached_channels = stasis_cache_dump(ast_channel_cache(), ast_channel_snapshot_type()))) {
                return NULL;
        }
 
@@ -1581,6 +1729,7 @@ char *ast_complete_channels(const char *line, const char *word, int pos, int sta
 
                if (!strncasecmp(word, snapshot->name, wordlen) && (++which > state)) {
                        ret = ast_strdup(snapshot->name);
+                       ao2_ref(msg, -1);
                        break;
                }
        }
@@ -1683,7 +1832,8 @@ static struct ast_cli_entry cli_cli[] = {
 
        AST_CLI_DEFINE(handle_core_set_debug_channel, "Enable/disable debugging on a channel"),
 
-       AST_CLI_DEFINE(handle_verbose, "Set level of debug/verbose chattiness"),
+       AST_CLI_DEFINE(handle_debug, "Set level of debug chattiness"),
+       AST_CLI_DEFINE(handle_verbose, "Set level of verbose chattiness"),
 
        AST_CLI_DEFINE(group_show_channels, "Display active channels with group(s)"),
 
@@ -1888,8 +2038,9 @@ static void cli_shutdown(void)
 /*! \brief initialize the _full_cmd string in * each of the builtins. */
 void ast_builtins_init(void)
 {
+       AST_VECTOR_INIT(&shutdown_commands, 0);
        ast_cli_register_multiple(cli_cli, ARRAY_LEN(cli_cli));
-       ast_register_atexit(cli_shutdown);
+       ast_register_cleanup(cli_shutdown);
 }
 
 /*!
@@ -2066,7 +2217,14 @@ static int cli_is_registered(struct ast_cli_entry *e)
        return 0;
 }
 
-static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
+static void remove_shutdown_command(struct ast_cli_entry *e)
+{
+       ast_rwlock_wrlock(&shutdown_commands_lock);
+       AST_VECTOR_REMOVE_ELEM_UNORDERED(&shutdown_commands, e, AST_VECTOR_ELEM_CLEANUP_NOOP);
+       ast_rwlock_unlock(&shutdown_commands_lock);
+}
+
+int ast_cli_unregister(struct ast_cli_entry *e)
 {
        if (e->inuse) {
                ast_log(LOG_WARNING, "Can't remove command that is in use\n");
@@ -2074,6 +2232,7 @@ static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *e
                AST_RWLIST_WRLOCK(&helpers);
                AST_RWLIST_REMOVE(&helpers, e, list);
                AST_RWLIST_UNLOCK(&helpers);
+               remove_shutdown_command(e);
                ast_free(e->_full_cmd);
                e->_full_cmd = NULL;
                if (e->handler) {
@@ -2088,7 +2247,7 @@ static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *e
        return 0;
 }
 
-static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
+int __ast_cli_register(struct ast_cli_entry *e, struct ast_module *module)
 {
        struct ast_cli_entry *cur;
        int i, lf, ret = -1;
@@ -2107,7 +2266,11 @@ static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
        }
 
        memset(&a, '\0', sizeof(a));
+
+       e->module = module;
+       /* No module reference needed here, the module called us. */
        e->handler(e, CLI_INIT, &a);
+
        /* XXX check that usage and command are filled up */
        s = ast_skip_blanks(e->command);
        s = e->command = ast_strdup(s);
@@ -2158,27 +2321,16 @@ done:
        return ret;
 }
 
-/* wrapper function, so we can unregister deprecated commands recursively */
-int ast_cli_unregister(struct ast_cli_entry *e)
-{
-       return __ast_cli_unregister(e, NULL);
-}
-
-/* wrapper function, so we can register deprecated commands recursively */
-int ast_cli_register(struct ast_cli_entry *e)
-{
-       return __ast_cli_register(e, NULL);
-}
-
 /*
  * register/unregister an array of entries.
  */
-int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
+int __ast_cli_register_multiple(struct ast_cli_entry *e, int len, struct ast_module *module)
 {
        int i, res = 0;
 
-       for (i = 0; i < len; i++)
-               res |= ast_cli_register(e + i);
+       for (i = 0; i < len; i++) {
+               res |= __ast_cli_register(e + i, module);
+       }
 
        return res;
 }
@@ -2292,6 +2444,13 @@ static char *parse_args(const char *s, int *argc, const char *argv[], int max, i
                return NULL;
 
        cur = duplicate;
+
+       /* Remove leading spaces from the command */
+       while (isspace(*s)) {
+               cur++;
+               s++;
+       }
+
        /* scan the original string copying into cur when needed */
        for (; *s ; s++) {
                if (x >= max - 1) {
@@ -2356,9 +2515,22 @@ int ast_cli_generatornummatches(const char *text, const char *word)
        return matches;
 }
 
+static void destroy_match_list(char **match_list, int matches)
+{
+       if (match_list) {
+               int idx;
+
+               for (idx = 1; idx < matches; ++idx) {
+                       ast_free(match_list[idx]);
+               }
+               ast_free(match_list);
+       }
+}
+
 char **ast_cli_completion_matches(const char *text, const char *word)
 {
        char **match_list = NULL, *retstr, *prevstr;
+       char **new_list;
        size_t match_list_len, max_equal, which, i;
        int matches = 0;
 
@@ -2367,14 +2539,19 @@ char **ast_cli_completion_matches(const char *text, const char *word)
        while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
                if (matches + 1 >= match_list_len) {
                        match_list_len <<= 1;
-                       if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
+                       new_list = ast_realloc(match_list, match_list_len * sizeof(*match_list));
+                       if (!new_list) {
+                               destroy_match_list(match_list, matches);
                                return NULL;
+                       }
+                       match_list = new_list;
                }
                match_list[++matches] = retstr;
        }
 
-       if (!match_list)
+       if (!match_list) {
                return match_list; /* NULL */
+       }
 
        /* Find the longest substring that is common to all results
         * (it is a candidate for completion), and store a copy in entry 0.
@@ -2387,20 +2564,23 @@ char **ast_cli_completion_matches(const char *text, const char *word)
                max_equal = i;
        }
 
-       if (!(retstr = ast_malloc(max_equal + 1))) {
-               ast_free(match_list);
+       retstr = ast_malloc(max_equal + 1);
+       if (!retstr) {
+               destroy_match_list(match_list, matches);
                return NULL;
        }
-
        ast_copy_string(retstr, match_list[1], max_equal + 1);
        match_list[0] = retstr;
 
        /* ensure that the array is NULL terminated */
        if (matches + 1 >= match_list_len) {
-               if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list)))) {
+               new_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list));
+               if (!new_list) {
                        ast_free(retstr);
+                       destroy_match_list(match_list, matches);
                        return NULL;
                }
+               match_list = new_list;
        }
        match_list[matches + 1] = NULL;
 
@@ -2492,7 +2672,9 @@ static char *__ast_cli_generator(const char *text, const char *word, int state,
                                        .n = state - matchnum,
                                        .argv = argv,
                                        .argc = x};
+                               ast_module_ref(e->module);
                                ret = e->handler(e, CLI_GENERATE, &a);
+                               ast_module_unref(e->module);
                        }
                        if (ret)
                                break;
@@ -2509,19 +2691,36 @@ char *ast_cli_generator(const char *text, const char *word, int state)
        return __ast_cli_generator(text, word, state, 1);
 }
 
+static int allowed_on_shutdown(struct ast_cli_entry *e)
+{
+       int found = 0;
+       int i;
+
+       ast_rwlock_rdlock(&shutdown_commands_lock);
+       for (i = 0; i < AST_VECTOR_SIZE(&shutdown_commands); ++i) {
+               if (e == AST_VECTOR_GET(&shutdown_commands, i)) {
+                       found = 1;
+                       break;
+               }
+       }
+       ast_rwlock_unlock(&shutdown_commands_lock);
+
+       return found;
+}
+
 int ast_cli_command_full(int uid, int gid, int fd, const char *s)
 {
        const char *args[AST_MAX_ARGS + 1];
-       struct ast_cli_entry *e;
+       struct ast_cli_entry *e = NULL;
        int x;
        char *duplicate = parse_args(s, &x, args + 1, AST_MAX_ARGS, NULL);
        char tmp[AST_MAX_ARGS + 1];
-       char *retval = NULL;
+       char *retval = CLI_FAILURE;
        struct ast_cli_args a = {
                .fd = fd, .argc = x, .argv = args+1 };
 
        if (duplicate == NULL)
-               return -1;
+               return RESULT_FAILURE;
 
        if (x < 1)      /* We need at least one entry, otherwise ignore */
                goto done;
@@ -2536,12 +2735,16 @@ int ast_cli_command_full(int uid, int gid, int fd, const char *s)
                goto done;
        }
 
+       if (ast_shutting_down() && !allowed_on_shutdown(e)) {
+               ast_cli(fd, "Command '%s' cannot be run during shutdown\n", s);
+               goto done;
+       }
+
        ast_join(tmp, sizeof(tmp), args + 1);
        /* Check if the user has rights to run this command. */
        if (!cli_has_permissions(uid, gid, tmp)) {
                ast_cli(fd, "You don't have permissions to run '%s' command\n", tmp);
-               ast_free(duplicate);
-               return 0;
+               goto done;
        }
 
        /*
@@ -2550,18 +2753,22 @@ int ast_cli_command_full(int uid, int gid, int fd, const char *s)
         */
        args[0] = (char *)e;
 
+       ast_module_ref(e->module);
        retval = e->handler(e, CLI_HANDLER, &a);
+       ast_module_unref(e->module);
 
        if (retval == CLI_SHOWUSAGE) {
                ast_cli(fd, "%s", S_OR(e->usage, "Invalid usage, but no usage information available.\n"));
-       } else {
-               if (retval == CLI_FAILURE)
-                       ast_cli(fd, "Command '%s' failed.\n", s);
+       } else if (retval == CLI_FAILURE) {
+               ast_cli(fd, "Command '%s' failed.\n", s);
        }
-       ast_atomic_fetchadd_int(&e->inuse, -1);
+
 done:
+       if (e) {
+               ast_atomic_fetchadd_int(&e->inuse, -1);
+       }
        ast_free(duplicate);
-       return 0;
+       return retval == CLI_SUCCESS ? RESULT_SUCCESS : RESULT_FAILURE;
 }
 
 int ast_cli_command_multiple_full(int uid, int gid, int fd, size_t size, const char *s)
@@ -2580,3 +2787,19 @@ int ast_cli_command_multiple_full(int uid, int gid, int fd, size_t size, const c
        }
        return count;
 }
+
+void ast_cli_print_timestr_fromseconds(int fd, int seconds, const char *prefix)
+{
+       print_uptimestr(fd, ast_tv(seconds, 0), prefix, 0);
+}
+
+int ast_cli_allow_at_shutdown(struct ast_cli_entry *e)
+{
+       int res;
+
+       ast_rwlock_wrlock(&shutdown_commands_lock);
+       res = AST_VECTOR_APPEND(&shutdown_commands, e);
+       ast_rwlock_unlock(&shutdown_commands_lock);
+
+       return res;
+}