Modules: Additional improvements to CLI completion.
[asterisk/asterisk.git] / main / cli.c
index 6d227fb..0896181 100644 (file)
  *
  * \brief Standard Command Line Interface
  *
- * \author Mark Spencer <markster@digium.com> 
+ * \author Mark Spencer <markster@digium.com>
  */
 
-#include "asterisk.h"
+/*! \li \ref cli.c uses the configuration file \ref cli_permissions.conf
+ * \addtogroup configuration_file Configuration Files
+ */
+
+/*!
+ * \page cli_permissions.conf cli_permissions.conf
+ * \verbinclude cli_permissions.conf.sample
+ */
 
-ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
+/*** MODULEINFO
+       <support_level>core</support_level>
+ ***/
+
+#include "asterisk.h"
 
 #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>
@@ -44,8 +54,13 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
 #include "asterisk/utils.h"
 #include "asterisk/app.h"
 #include "asterisk/lock.h"
-#include "editline/readline/readline.h"
 #include "asterisk/threadstorage.h"
+#include "asterisk/translate.h"
+#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.
@@ -77,23 +92,24 @@ AST_MUTEX_DEFINE_STATIC(permsconfiglock);
 static AST_RWLIST_HEAD_STATIC(cli_perms, usergroup_cli_perm);
 
 /*!
- * \brief map a debug or verbose value to a filename
+ * \brief map a debug or verbose level to a module name
  */
-struct ast_debug_file {
+struct module_level {
        unsigned int level;
-       AST_RWLIST_ENTRY(ast_debug_file) entry;
-       char filename[0];
+       AST_RWLIST_ENTRY(module_level) entry;
+       char module[0];
 };
 
-AST_RWLIST_HEAD(debug_file_list, ast_debug_file);
+AST_RWLIST_HEAD(module_level_list, module_level);
 
-/*! list of filenames and their debug settings */
-static struct debug_file_list debug_files;
-/*! list of filenames and their verbose settings */
-static struct debug_file_list verbose_files;
+/*! list of module names and their debug levels */
+static struct module_level_list debug_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
 
@@ -115,38 +131,26 @@ void ast_cli(int fd, const char *fmt, ...)
        }
 }
 
-unsigned int ast_debug_get_by_file(const char *file) 
+unsigned int ast_debug_get_by_module(const char *module)
 {
-       struct ast_debug_file *adf;
+       struct module_level *ml;
        unsigned int res = 0;
 
-       AST_RWLIST_RDLOCK(&debug_files);
-       AST_LIST_TRAVERSE(&debug_files, adf, entry) {
-               if (!strncasecmp(adf->filename, file, strlen(adf->filename))) {
-                       res = adf->level;
+       AST_RWLIST_RDLOCK(&debug_modules);
+       AST_LIST_TRAVERSE(&debug_modules, ml, entry) {
+               if (!strcasecmp(ml->module, module)) {
+                       res = ml->level;
                        break;
                }
        }
-       AST_RWLIST_UNLOCK(&debug_files);
+       AST_RWLIST_UNLOCK(&debug_modules);
 
        return res;
 }
 
-unsigned int ast_verbose_get_by_file(const char *file) 
+unsigned int ast_verbose_get_by_module(const char *module)
 {
-       struct ast_debug_file *adf;
-       unsigned int res = 0;
-
-       AST_RWLIST_RDLOCK(&verbose_files);
-       AST_LIST_TRAVERSE(&verbose_files, adf, entry) {
-               if (!strncasecmp(adf->filename, file, strlen(file))) {
-                       res = adf->level;
-                       break;
-               }
-       }
-       AST_RWLIST_UNLOCK(&verbose_files);
-
-       return res;
+       return 0;
 }
 
 /*! \internal
@@ -219,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>" */
@@ -253,16 +235,19 @@ 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;
        }
+       ast_cli(a->fd, "Loaded %s\n", a->argv[e->args]);
        return CLI_SUCCESS;
 }
 
@@ -280,42 +265,85 @@ 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);
                return CLI_SUCCESS;
        }
        for (x = e->args; x < a->argc; x++) {
-               int res = ast_module_reload(a->argv[x]);
-               /* XXX reload has multiple error returns, including -1 on error and 2 on success */
+               enum ast_module_reload_result res = ast_module_reload(a->argv[x]);
                switch (res) {
-               case 0:
+               case AST_MODULE_RELOAD_NOT_FOUND:
                        ast_cli(a->fd, "No such module '%s'\n", a->argv[x]);
                        break;
-               case 1:
-                       ast_cli(a->fd, "Module '%s' does not support reload\n", a->argv[x]);
+               case AST_MODULE_RELOAD_NOT_IMPLEMENTED:
+                       ast_cli(a->fd, "The module '%s' does not support reloads\n", a->argv[x]);
+                       break;
+               case AST_MODULE_RELOAD_QUEUED:
+                       ast_cli(a->fd, "Asterisk cannot reload a module yet; request queued\n");
+                       break;
+               case AST_MODULE_RELOAD_ERROR:
+                       ast_cli(a->fd, "The module '%s' reported a reload failure\n", a->argv[x]);
+                       break;
+               case AST_MODULE_RELOAD_IN_PROGRESS:
+                       ast_cli(a->fd, "A module reload request is already in progress; please be patient\n");
+                       break;
+               case AST_MODULE_RELOAD_UNINITIALIZED:
+                       ast_cli(a->fd, "The module '%s' was not properly initialized. Before reloading"
+                                       " the module, you must run \"module load %s\" and fix whatever is"
+                                       " preventing the module from being initialized.\n", a->argv[x], a->argv[x]);
+                       break;
+               case AST_MODULE_RELOAD_SUCCESS:
+                       ast_cli(a->fd, "Module '%s' reloaded successfully.\n", a->argv[x]);
                        break;
                }
        }
        return CLI_SUCCESS;
 }
 
-/*! 
- * \brief Find the debug or verbose file setting 
- * \arg debug 1 for debug, 0 for verbose
+static char *handle_core_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "core reload";
+               e->usage =
+                       "Usage: core reload\n"
+                       "       Execute a global reload.\n";
+               return NULL;
+
+       case CLI_GENERATE:
+               return NULL;
+       }
+
+       if (a->argc != e->args) {
+               return CLI_SHOWUSAGE;
+       }
+
+       ast_module_reload(NULL);
+
+       return CLI_SUCCESS;
+}
+
+/*!
+ * \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 ast_debug_file *find_debug_file(const char *fn, unsigned int debug)
+static struct module_level *find_module_level(const char *module, struct module_level_list *mll)
 {
-       struct ast_debug_file *df = NULL;
-       struct debug_file_list *dfl = debug ? &debug_files : &verbose_files;
+       struct module_level *ml;
 
-       AST_LIST_TRAVERSE(dfl, df, entry) {
-               if (!strcasecmp(df->filename, fn))
-                       break;
+       AST_LIST_TRAVERSE(mll, ml, entry) {
+               if (!strcasecmp(ml->module, module))
+                       return ml;
        }
 
-       return df;
+       return NULL;
 }
 
 static char *complete_number(const char *partial, unsigned int min, unsigned int max, int n)
@@ -323,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;
@@ -358,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;
        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 debug_file_list *dfl;
-       struct ast_debug_file *adf;
-       const char *fn;
+       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> [filename]\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"
-                       "       sets a filename 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";
+                       "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"
+                       "       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))) {
@@ -414,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;
        }
@@ -425,92 +469,201 @@ 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";
-       } else {
-               dst = &option_verbose;
-               oldval = option_verbose;
-               what = "Verbosity";
        }
-       if (argc == e->args + 1 && !strcasecmp(argv[e->args], "off")) {
-               unsigned int debug = (*what == 'C');
+
+       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;
+               }
 
-               dfl = debug ? &debug_files : &verbose_files;
+               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(dfl);
-               while ((adf = AST_RWLIST_REMOVE_HEAD(dfl, entry)))
-                       ast_free(adf);
-               ast_clear_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
-               AST_RWLIST_UNLOCK(dfl);
+                       if (3 < mod_len && !strcasecmp(mod + mod_len - 3, ".so")) {
+                               mod[mod_len - 3] = '\0';
+                       }
 
-               goto done;
-       }
-       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) {
-               unsigned int debug = (*what == 'C');
-               dfl = debug ? &debug_files : &verbose_files;
+                       AST_RWLIST_WRLOCK(&debug_modules);
 
-               fn = argv[e->args + atleast + 1];
+                       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_RWLIST_WRLOCK(dfl);
+                       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);
 
-               if ((adf = find_debug_file(fn, debug)) && !newlevel) {
-                       AST_RWLIST_REMOVE(dfl, adf, entry);
-                       if (AST_RWLIST_EMPTY(dfl))
-                               ast_clear_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
-                       AST_RWLIST_UNLOCK(dfl);
-                       ast_cli(fd, "%s was %d and has been set to 0 for '%s'\n", what, adf->level, fn);
-                       ast_free(adf);
                        return CLI_SUCCESS;
                }
+       }
 
-               if (adf) {
-                       if ((atleast && newlevel < adf->level) || adf->level == newlevel) {
-                               ast_cli(fd, "%s is %d for '%s'\n", what, adf->level, fn);
-                               AST_RWLIST_UNLOCK(dfl);
-                               return CLI_SUCCESS;
-                       }
-               } else if (!(adf = ast_calloc(1, sizeof(*adf) + strlen(fn) + 1))) {
-                       AST_RWLIST_UNLOCK(dfl);
-                       return CLI_FAILURE;
+       /* 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;
+       }
 
-               oldval = adf->level;
-               adf->level = newlevel;
-               strcpy(adf->filename, fn);
+       /* Report debug level status */
+       status_debug_verbose(a, "Core debug", oldval, option_debug);
 
-               ast_set_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
+       return CLI_SUCCESS;
+}
 
-               AST_RWLIST_INSERT_TAIL(dfl, adf, entry);
-               AST_RWLIST_UNLOCK(dfl);
+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], "") : "";
 
-               ast_cli(fd, "%s was %d and has been set to %d for '%s'\n", what, oldval, adf->level, adf->filename);
+       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;
 
-               return CLI_SUCCESS;
+       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 (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");
+                       }
+               } 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");
+                       }
+               }
+               return NULL;
        }
+       /* all the above return, so we proceed with the handler.
+        * we are guaranteed to be called with argc >= e->args;
+        */
 
-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);
+       if (a->argc <= e->args) {
+               return CLI_SHOWUSAGE;
        }
 
+       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;
+               }
+       }
+
+       /* 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;
+       }
+
+       /* Report verbose level status */
+       status_debug_verbose(a, "Console verbose", oldval, newlevel);
+
        return CLI_SUCCESS;
 }
 
@@ -519,7 +672,7 @@ static char *handle_logger_mute(struct ast_cli_entry *e, int cmd, struct ast_cli
        switch (cmd) {
        case CLI_INIT:
                e->command = "logger mute";
-               e->usage = 
+               e->usage =
                        "Usage: logger mute\n"
                        "       Disables logging output to the current console, making it possible to\n"
                        "       gather information without being disturbed by scrolling lines.\n";
@@ -559,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;
@@ -582,23 +735,28 @@ static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args
                        ast_cli(a->fd, "Unable to unload resource %s\n", a->argv[x]);
                        return CLI_FAILURE;
                }
+               ast_cli(a->fd, "Unloaded %s\n", a->argv[x]);
        }
+
        return CLI_SUCCESS;
 }
 
-#define MODLIST_FORMAT  "%-30s %-40.40s %-10d\n"
-#define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\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 *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);
+               ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt,
+                               status, ast_module_support_level_to_string(support_level));
                return 1;
-       } 
+       }
        return 0;
 }
 
@@ -613,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)
@@ -686,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;
 }
 
@@ -706,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
@@ -720,10 +883,10 @@ static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_arg
                like = a->argv[e->args];
        else
                return CLI_SHOWUSAGE;
-               
+
        ast_mutex_lock(&climodentrylock);
        climodentryfd = a->fd; /* global, protected by climodentrylock */
-       ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
+       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);
@@ -734,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;
 
@@ -741,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"
@@ -751,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 */
@@ -770,18 +934,18 @@ 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()));
        }
-   
+
        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;
@@ -795,9 +959,10 @@ static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
 #define VERBOSE_FORMAT_STRING  "%-20.20s %-20.20s %-16.16s %4d %-7.7s %-12.12s %-25.25s %-15.15s %8.8s %-11.11s %-11.11s %-20.20s\n"
 #define VERBOSE_FORMAT_STRING2 "%-20.20s %-20.20s %-16.16s %-4.4s %-7.7s %-12.12s %-25.25s %-15.15s %8.8s %-11.11s %-11.11s %-20.20s\n"
 
-       struct ast_channel *c = NULL;
+       RAII_VAR(struct ao2_container *, channels, NULL, ao2_cleanup);
+       struct ao2_iterator it_chans;
+       struct stasis_message *msg;
        int numchans = 0, concise = 0, verbose = 0, count = 0;
-       struct ast_channel_iterator *iter = NULL;
 
        switch (cmd) {
        case CLI_INIT:
@@ -829,29 +994,28 @@ static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
        } else if (a->argc != e->args - 1)
                return CLI_SHOWUSAGE;
 
+
+       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;
+       }
+
        if (!count) {
                if (!concise && !verbose)
                        ast_cli(a->fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
                else if (verbose)
-                       ast_cli(a->fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data", 
-                               "CallerID", "Duration", "Accountcode", "PeerAccount", "BridgedTo");
-       }
-
-       if (!count && !(iter = ast_channel_iterator_all_new())) {
-               return CLI_FAILURE;
+                       ast_cli(a->fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
+                               "CallerID", "Duration", "Accountcode", "PeerAccount", "BridgeID");
        }
 
-       for (; iter && (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
-               struct ast_channel *bc;
-               char durbuf[10] = "-";
-
-               ast_channel_lock(c);
-
-               bc = ast_bridged_channel(c);
+       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[16] = "-";
 
                if (!count) {
-                       if ((concise || verbose)  && c->cdr && !ast_tvzero(c->cdr->start)) {
-                               int duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
+                       if ((concise || verbose)  && !ast_tvzero(cs->creationtime)) {
+                               int duration = (int)(ast_tvdiff_ms(ast_tvnow(), cs->creationtime) / 1000);
                                if (verbose) {
                                        int durh = duration / 3600;
                                        int durm = (duration % 3600) / 60;
@@ -859,53 +1023,51 @@ static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                                        snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
                                } else {
                                        snprintf(durbuf, sizeof(durbuf), "%d", duration);
-                               }                               
+                               }
                        }
                        if (concise) {
-                               ast_cli(a->fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
-                                       c->appl ? c->appl : "(None)",
-                                       S_OR(c->data, ""),      /* XXX different from verbose ? */
-                                       S_OR(c->cid.cid_num, ""),
-                                       S_OR(c->accountcode, ""),
-                                       S_OR(c->peeraccount, ""),
-                                       c->amaflags, 
+                               ast_cli(a->fd, CONCISE_FORMAT_STRING, cs->name, cs->context, cs->exten, cs->priority, ast_state2str(cs->state),
+                                       S_OR(cs->appl, "(None)"),
+                                       cs->data,
+                                       cs->caller_number,
+                                       cs->accountcode,
+                                       cs->peeraccount,
+                                       cs->amaflags,
                                        durbuf,
-                                       bc ? bc->name : "(None)",
-                                       c->uniqueid);
+                                       cs->bridgeid,
+                                       cs->uniqueid);
                        } else if (verbose) {
-                               ast_cli(a->fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
-                                       c->appl ? c->appl : "(None)",
-                                       c->data ? S_OR(c->data, "(Empty)" ): "(None)",
-                                       S_OR(c->cid.cid_num, ""),
+                               ast_cli(a->fd, VERBOSE_FORMAT_STRING, cs->name, cs->context, cs->exten, cs->priority, ast_state2str(cs->state),
+                                       S_OR(cs->appl, "(None)"),
+                                       S_OR(cs->data, "(Empty)"),
+                                       cs->caller_number,
                                        durbuf,
-                                       S_OR(c->accountcode, ""),
-                                       S_OR(c->peeraccount, ""),
-                                       bc ? bc->name : "(None)");
+                                       cs->accountcode,
+                                       cs->peeraccount,
+                                       cs->bridgeid);
                        } else {
                                char locbuf[40] = "(None)";
                                char appdata[40] = "(None)";
-                               
-                               if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten)) 
-                                       snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
-                               if (c->appl)
-                                       snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, S_OR(c->data, ""));
-                               ast_cli(a->fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
+
+                               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 (!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);
                        }
                }
-               ast_channel_unlock(c);
-       }
-
-       if (iter) {
-               ast_channel_iterator_destroy(iter);
        }
+       ao2_iterator_destroy(&it_chans);
 
        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()));
 
@@ -913,7 +1075,7 @@ static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
        }
 
        return CLI_SUCCESS;
-       
+
 #undef FORMAT_STRING
 #undef FORMAT_STRING2
 #undef CONCISE_FORMAT_STRING
@@ -923,27 +1085,50 @@ 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:
                e->command = "channel request hangup";
                e->usage =
-                       "Usage: channel request hangup <channel>\n"
+                       "Usage: channel request hangup <channel>|<all>\n"
                        "       Request that a channel be hung up. The hangup takes effect\n"
-                       "       the next time the driver reads or writes from the channel\n";
+                       "       the next time the driver reads or writes from the channel.\n"
+                       "       If 'all' is specified instead of a channel name, all channels\n"
+                       "       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) {
                return CLI_SHOWUSAGE;
        }
 
-       if ((c = ast_channel_get_by_name(a->argv[3]))) {
+       if (!strcasecmp(a->argv[3], "all")) {
+               struct ast_channel_iterator *iter = NULL;
+               if (!(iter = ast_channel_iterator_all_new())) {
+                       return CLI_FAILURE;
+               }
+               for (; iter && (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
+                       ast_channel_lock(c);
+                       ast_cli(a->fd, "Requested Hangup on channel '%s'\n", ast_channel_name(c));
+                       ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
+                       ast_channel_unlock(c);
+               }
+               ast_channel_iterator_destroy(iter);
+       } else if ((c = ast_channel_get_by_name(a->argv[3]))) {
                ast_channel_lock(c);
-               ast_cli(a->fd, "Requested Hangup on channel '%s'\n", c->name);
+               ast_cli(a->fd, "Requested Hangup on channel '%s'\n", ast_channel_name(c));
                ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
                ast_channel_unlock(c);
                c = ast_channel_unref(c);
@@ -1103,11 +1288,11 @@ static char *handle_commandmatchesarray(struct ast_cli_entry *e, int cmd, struct
        int len = 0;
        char **matches;
        int x, matchlen;
-       
+
        switch (cmd) {
        case CLI_INIT:
                e->command = "_command matchesarray";
-               e->usage = 
+               e->usage =
                        "Usage: _command matchesarray \"<line>\" text \n"
                        "       This function is used internally to help with command completion and should.\n"
                        "       never be called by the user directly.\n";
@@ -1128,7 +1313,7 @@ static char *handle_commandmatchesarray(struct ast_cli_entry *e, int cmd, struct
                        if (len + matchlen >= buflen) {
                                buflen += matchlen * 3;
                                obuf = buf;
-                               if (!(buf = ast_realloc(obuf, buflen))) 
+                               if (!(buf = ast_realloc(obuf, buflen)))
                                        /* Memory allocation failure...  Just free old buffer and be done */
                                        ast_free(obuf);
                        }
@@ -1158,7 +1343,7 @@ static char *handle_commandnummatches(struct ast_cli_entry *e, int cmd, struct a
        switch (cmd) {
        case CLI_INIT:
                e->command = "_command nummatches";
-               e->usage = 
+               e->usage =
                        "Usage: _command nummatches \"<line>\" text \n"
                        "       This function is used internally to help with command completion and should.\n"
                        "       never be called by the user directly.\n";
@@ -1183,7 +1368,7 @@ static char *handle_commandcomplete(struct ast_cli_entry *e, int cmd, struct ast
        switch (cmd) {
        case CLI_INIT:
                e->command = "_command complete";
-               e->usage = 
+               e->usage =
                        "Usage: _command complete \"<line>\" text state\n"
                        "       This function is used internally to help with command completion and should.\n"
                        "       never be called by the user directly.\n";
@@ -1214,16 +1399,16 @@ static int channel_set_debug(void *obj, void *arg, void *data, int flags)
 
        ast_channel_lock(chan);
 
-       if (!(chan->fin & DEBUGCHAN_FLAG) || !(chan->fout & DEBUGCHAN_FLAG)) {
+       if (!(ast_channel_fin(chan) & DEBUGCHAN_FLAG) || !(ast_channel_fout(chan) & DEBUGCHAN_FLAG)) {
                if (args->is_off) {
-                       chan->fin &= ~DEBUGCHAN_FLAG;
-                       chan->fout &= ~DEBUGCHAN_FLAG;
+                       ast_channel_fin_set(chan, ast_channel_fin(chan) & ~DEBUGCHAN_FLAG);
+                       ast_channel_fout_set(chan, ast_channel_fout(chan) & ~DEBUGCHAN_FLAG);
                } else {
-                       chan->fin |= DEBUGCHAN_FLAG;
-                       chan->fout |= DEBUGCHAN_FLAG;
+                       ast_channel_fin_set(chan, ast_channel_fin(chan) | DEBUGCHAN_FLAG);
+                       ast_channel_fout_set(chan, ast_channel_fout(chan) | DEBUGCHAN_FLAG);
                }
                ast_cli(args->fd, "Debugging %s on channel %s\n", args->is_off ? "disabled" : "enabled",
-                               chan->name);
+                               ast_channel_name(chan));
        }
 
        ast_channel_unlock(chan);
@@ -1234,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,
        };
@@ -1246,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)) {
@@ -1314,46 +1506,61 @@ static char *handle_nodebugchan_deprecated(struct ast_cli_entry *e, int cmd, str
 
        return res;
 }
-               
+
 static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
 {
-       struct ast_channel *c=NULL;
+       struct ast_channel *chan;
        struct timeval now;
-       struct ast_str *out = ast_str_thread_get(&ast_str_thread_global_buf, 16);
        char cdrtime[256];
-       char nf[256], wf[256], rf[256];
+       struct ast_str *obuf;/*!< Buffer for CDR variables. */
+       struct ast_str *output;/*!< Accumulation buffer for all output. */
        long elapsed_seconds=0;
        int hour=0, min=0, sec=0;
-#ifdef CHANNEL_TRACE
-       int trace_enabled;
-#endif
+       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:
                e->command = "core show channel";
-               e->usage = 
+               e->usage =
                        "Usage: core show channel <channel>\n"
                        "       Shows lots of information about the specified channel.\n";
                return NULL;
        case CLI_GENERATE:
                return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
        }
-       
+
        if (a->argc != 4) {
                return CLI_SHOWUSAGE;
        }
 
-       now = ast_tvnow();
+       obuf = ast_str_thread_get(&ast_str_thread_global_buf, 16);
+       if (!obuf) {
+               return CLI_FAILURE;
+       }
 
-       if (!(c = ast_channel_get_by_name(a->argv[3]))) {
+       output = ast_str_create(8192);
+       if (!output) {
+               return CLI_FAILURE;
+       }
+
+       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;
        }
 
-       ast_channel_lock(c);
+       now = ast_tvnow();
+       ast_channel_lock(chan);
 
-       if (c->cdr) {
-               elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
+       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;
@@ -1362,7 +1569,17 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                strcpy(cdrtime, "N/A");
        }
 
-       ast_cli(a->fd, 
+       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"
                "           Type: %s\n"
@@ -1370,22 +1587,21 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                "       LinkedID: %s\n"
                "      Caller ID: %s\n"
                " Caller ID Name: %s\n"
+               "Connected Line ID: %s\n"
+               "Connected Line ID Name: %s\n"
+               "Eff. Connected Line ID: %s\n"
+               "Eff. Connected Line ID Name: %s\n"
                "    DNID Digits: %s\n"
                "       Language: %s\n"
-               "          State: %s (%d)\n"
-               "          Rings: %d\n"
+               "          State: %s (%u)\n"
                "  NativeFormats: %s\n"
                "    WriteFormat: %s\n"
                "     ReadFormat: %s\n"
-               " WriteTranscode: %s\n"
-               "  ReadTranscode: %s\n"
-               "1st File Descriptor: %d\n"
-               "      Frames in: %d%s\n"
-               "     Frames out: %d%s\n"
+               " WriteTranscode: %s %s\n"
+               "  ReadTranscode: %s %s\n"
                " Time to Hangup: %ld\n"
                "   Elapsed Time: %s\n"
-               "  Direct Bridge: %s\n"
-               "Indirect Bridge: %s\n"
+               "      Bridge ID: %s\n"
                " --   PBX   --\n"
                "        Context: %s\n"
                "      Extension: %s\n"
@@ -1394,44 +1610,83 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                "   Pickup Group: %llu\n"
                "    Application: %s\n"
                "           Data: %s\n"
-               "    Blocking in: %s\n",
-               c->name, c->tech->type, c->uniqueid, c->linkedid,
-               S_OR(c->cid.cid_num, "(N/A)"),
-               S_OR(c->cid.cid_name, "(N/A)"),
-               S_OR(c->cid.cid_dnid, "(N/A)"), 
-               c->language,    
-               ast_state2str(c->_state), c->_state, c->rings, 
-               ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats), 
-               ast_getformatname_multiple(wf, sizeof(wf), c->writeformat), 
-               ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
-               c->writetrans ? "Yes" : "No",
-               c->readtrans ? "Yes" : "No",
-               c->fds[0],
-               c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
-               c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
-               (long)c->whentohangup.tv_sec,
-               cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>", 
-               c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
-               ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
-               (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
-       
-       if (pbx_builtin_serialize_variables(c, &out)) {
-               ast_cli(a->fd,"      Variables:\n%s\n", ast_str_buffer(out));
-       }
-
-       if (c->cdr && ast_cdr_serialize_variables(c->cdr, &out, '=', '\n', 1)) {
-               ast_cli(a->fd,"  CDR Variables:\n%s\n", ast_str_buffer(out));
-       }
-
-#ifdef CHANNEL_TRACE
-       trace_enabled = ast_channel_trace_is_enabled(c);
-       ast_cli(a->fd, "  Context Trace: %s\n", trace_enabled ? "Enabled" : "Disabled");
-       if (trace_enabled && ast_channel_trace_serialize(c, &out))
-               ast_cli(a->fd, "          Trace:\n%s\n", ast_str_buffer(out));
-#endif
-
-       ast_channel_unlock(c);
-       c = ast_channel_unref(c);
+               " Call Identifer: %s\n",
+               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,
+               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(ast_channel_varshead(chan), var, entries) {
+               ast_str_append(&output, 0, "%s=%s\n", ast_var_name(var), ast_var_value(var));
+       }
+
+       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;
 }
@@ -1454,32 +1709,33 @@ char *ast_cli_complete(const char *word, const char * const choices[], int state
 
 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
 {
-       struct ast_channel *c = NULL;
-       int which = 0;
-       char notfound = '\0';
-       char *ret = &notfound; /* so NULL can break the loop */
-       struct ast_channel_iterator *iter;
+       int wordlen = strlen(word), which = 0;
+       RAII_VAR(struct ao2_container *, cached_channels, NULL, ao2_cleanup);
+       char *ret = NULL;
+       struct ao2_iterator iter;
+       struct stasis_message *msg;
 
        if (pos != rpos) {
                return NULL;
        }
 
-       if (!(iter = ast_channel_iterator_by_name_new(word, strlen(word)))) {
+       if (!(cached_channels = stasis_cache_dump(ast_channel_cache(), ast_channel_snapshot_type()))) {
                return NULL;
        }
 
-       while (ret == &notfound && (c = ast_channel_iterator_next(iter))) {
-               if (++which > state) {
-                       ast_channel_lock(c);
-                       ret = ast_strdup(c->name);
-                       ast_channel_unlock(c);
+       iter = ao2_iterator_init(cached_channels, 0);
+       for (; (msg = ao2_iterator_next(&iter)); ao2_ref(msg, -1)) {
+               struct ast_channel_snapshot *snapshot = stasis_message_data(msg);
+
+               if (!strncasecmp(word, snapshot->name, wordlen) && (++which > state)) {
+                       ret = ast_strdup(snapshot->name);
+                       ao2_ref(msg, -1);
+                       break;
                }
-               ast_channel_unref(c);
        }
+       ao2_iterator_destroy(&iter);
 
-       ast_channel_iterator_destroy(iter);
-
-       return ret == &notfound ? NULL : ret;
+       return ret;
 }
 
 static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
@@ -1494,7 +1750,7 @@ static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cl
        switch (cmd) {
        case CLI_INIT:
                e->command = "group show channels";
-               e->usage = 
+               e->usage =
                        "Usage: group show channels [pattern]\n"
                        "       Lists all currently active channels with channel group(s) specified.\n"
                        "       Optional regular expression pattern is matched to group names for each\n"
@@ -1506,7 +1762,7 @@ static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cl
 
        if (a->argc < 3 || a->argc > 4)
                return CLI_SHOWUSAGE;
-       
+
        if (a->argc == 4) {
                if (regcomp(&regexbuf, a->argv[3], REG_EXTENDED | REG_NOSUB))
                        return CLI_SHOWUSAGE;
@@ -1516,18 +1772,18 @@ static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cl
        ast_cli(a->fd, FORMAT_STRING, "Channel", "Group", "Category");
 
        ast_app_group_list_rdlock();
-       
+
        gi = ast_app_group_list_head();
        while (gi) {
                if (!havepattern || !regexec(&regexbuf, gi->group, 0, NULL, 0)) {
-                       ast_cli(a->fd, FORMAT_STRING, gi->chan->name, gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category));
+                       ast_cli(a->fd, FORMAT_STRING, ast_channel_name(gi->chan), gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category));
                        numchans++;
                }
                gi = AST_LIST_NEXT(gi, group_list);
        }
-       
+
        ast_app_group_list_unlock();
-       
+
        if (havepattern)
                regfree(&regexbuf);
 
@@ -1536,6 +1792,28 @@ static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cl
 #undef FORMAT_STRING
 }
 
+static char *handle_cli_wait_fullybooted(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
+{
+       switch (cmd) {
+       case CLI_INIT:
+               e->command = "core waitfullybooted";
+               e->usage =
+                       "Usage: core waitfullybooted\n"
+                       "       Wait until Asterisk has fully booted.\n";
+               return NULL;
+       case CLI_GENERATE:
+               return NULL;
+       }
+
+       while (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
+               usleep(100);
+       }
+
+       ast_cli(a->fd, "Asterisk has fully booted.\n");
+
+       return CLI_SUCCESS;
+}
+
 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
 
 static struct ast_cli_entry cli_cli[] = {
@@ -1554,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)"),
 
@@ -1566,7 +1845,9 @@ static struct ast_cli_entry cli_cli[] = {
 
        AST_CLI_DEFINE(handle_load, "Load a module by name"),
 
-       AST_CLI_DEFINE(handle_reload, "Reload configuration"),
+       AST_CLI_DEFINE(handle_reload, "Reload configuration for a module"),
+
+       AST_CLI_DEFINE(handle_core_reload, "Global reload"),
 
        AST_CLI_DEFINE(handle_unload, "Unload a module by name"),
 
@@ -1579,6 +1860,8 @@ static struct ast_cli_entry cli_cli[] = {
        AST_CLI_DEFINE(handle_cli_show_permissions, "Show CLI permissions"),
 
        AST_CLI_DEFINE(handle_cli_check_permissions, "Try a permissions config for a user"),
+
+       AST_CLI_DEFINE(handle_cli_wait_fullybooted, "Wait for Asterisk to be fully booted"),
 };
 
 /*!
@@ -1686,7 +1969,7 @@ int ast_cli_perms_init(int reload)
                AST_RWLIST_WRLOCK(&cli_perms);
                AST_LIST_TRAVERSE(&cli_perms, cp_entry, list) {
                        if ((pw && cp_entry->uid == pw->pw_uid) || (gr && cp_entry->gid == gr->gr_gid)) {
-                               /* if it is duplicated, just added this new settings, to 
+                               /* if it is duplicated, just added this new settings, to
                                the current list. */
                                user_group = cp_entry;
                                break;
@@ -1747,10 +2030,17 @@ int ast_cli_perms_init(int reload)
        return 0;
 }
 
+static void cli_shutdown(void)
+{
+       ast_cli_unregister_multiple(cli_cli, ARRAY_LEN(cli_cli));
+}
+
 /*! \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_cleanup(cli_shutdown);
 }
 
 /*!
@@ -1773,20 +2063,30 @@ static int word_match(const char *cmd, const char *cli_word)
                return -1;
        if (!strchr(cli_rsvd, cli_word[0])) /* normal match */
                return (strcasecmp(cmd, cli_word) == 0) ? 1 : -1;
-       /* regexp match, takes [foo|bar] or {foo|bar} */
        l = strlen(cmd);
        /* wildcard match - will extend in the future */
        if (l > 0 && cli_word[0] == '%') {
                return 1;       /* wildcard */
        }
+
+       /* Start a search for the command entered against the cli word in question */
        pos = strcasestr(cli_word, cmd);
-       if (pos == NULL) /* not found, say ok if optional */
-               return cli_word[0] == '[' ? 0 : -1;
-       if (pos == cli_word)    /* no valid match at the beginning */
-               return -1;
-       if (strchr(cli_rsvd, pos[-1]) && strchr(cli_rsvd, pos[l]))
-               return 1;       /* valid match */
-       return -1;      /* not found */
+       while (pos) {
+
+               /*
+                *Check if the word matched with is surrounded by reserved characters on both sides
+                * and isn't at the beginning of the cli_word since that would make it check in a location we shouldn't know about.
+                * If it is surrounded by reserved chars and isn't at the beginning, it's a match.
+                */
+               if (pos != cli_word && strchr(cli_rsvd, pos[-1]) && strchr(cli_rsvd, pos[l])) {
+                       return 1;       /* valid match */
+               }
+
+               /* Ok, that one didn't match, strcasestr to the next appearance of the command and start over.*/
+               pos = strcasestr(pos + 1, cmd);
+       }
+       /* If no matches were found over the course of the while loop, we hit the end of the string. It's a mismatch. */
+       return -1;
 }
 
 /*! \brief if word is a valid prefix for token, returns the pos-th
@@ -1838,7 +2138,7 @@ static char *is_prefix(const char *word, const char *token,
  * \param cmds
  * \param match_type has 3 possible values:
  *      0       returns if the search key is equal or longer than the entry.
- *                         note that trailing optional arguments are skipped.
+ *                         note that trailing optional arguments are skipped.
  *      -1      true if the mismatch is on the last word XXX not true!
  *      1       true only on complete, exact match.
  *
@@ -1905,7 +2205,26 @@ static char *find_best(const char *argv[])
        return cmdline;
 }
 
-static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
+static int cli_is_registered(struct ast_cli_entry *e)
+{
+       struct ast_cli_entry *cur = NULL;
+
+       while ((cur = cli_next(cur))) {
+               if (cur == e) {
+                       return 1;
+               }
+       }
+       return 0;
+}
+
+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");
@@ -1913,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) {
@@ -1927,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;
@@ -1936,8 +2256,21 @@ static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
        char **dst = (char **)e->cmda;  /* need to cast as the entry is readonly */
        char *s;
 
+       AST_RWLIST_WRLOCK(&helpers);
+
+       if (cli_is_registered(e)) {
+               ast_log(LOG_WARNING, "Command '%s' already registered (the same ast_cli_entry)\n",
+                       S_OR(e->_full_cmd, e->command));
+               ret = 0;  /* report success */
+               goto done;
+       }
+
        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);
@@ -1950,15 +2283,17 @@ static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
                s = ast_skip_blanks(s);
        }
        *dst++ = NULL;
-       
-       AST_RWLIST_WRLOCK(&helpers);
-       
+
        if (find_cli(e->cmda, 1)) {
-               ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", S_OR(e->_full_cmd, e->command));
+               ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n",
+                       S_OR(e->_full_cmd, e->command));
                goto done;
        }
-       if (set_full_cmd(e))
+       if (set_full_cmd(e)) {
+               ast_log(LOG_WARNING, "Error registering CLI Command '%s'\n",
+                       S_OR(e->_full_cmd, e->command));
                goto done;
+       }
 
        lf = e->cmdlen;
        AST_RWLIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
@@ -1966,43 +2301,36 @@ static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
                if (lf < len)
                        len = lf;
                if (strncasecmp(e->_full_cmd, cur->_full_cmd, len) < 0) {
-                       AST_RWLIST_INSERT_BEFORE_CURRENT(e, list); 
+                       AST_RWLIST_INSERT_BEFORE_CURRENT(e, list);
                        break;
                }
        }
        AST_RWLIST_TRAVERSE_SAFE_END;
 
        if (!cur)
-               AST_RWLIST_INSERT_TAIL(&helpers, e, list); 
+               AST_RWLIST_INSERT_TAIL(&helpers, e, list);
        ret = 0;        /* success */
 
 done:
        AST_RWLIST_UNLOCK(&helpers);
+       if (ret) {
+               ast_free(e->command);
+               e->command = NULL;
+       }
 
        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;
 }
@@ -2040,7 +2368,8 @@ static char *help1(int fd, const char * const match[], int locked)
                        continue;
                if (match && strncasecmp(matchstr, e->_full_cmd, len))
                        continue;
-               ast_cli(fd, "%30.30s %s\n", e->_full_cmd, S_OR(e->summary, "<no description available>"));
+               ast_cli(fd, "%-30s -- %s\n", e->_full_cmd,
+                       S_OR(e->summary, "<no description available>"));
                found++;
        }
        if (!locked)
@@ -2115,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) {
@@ -2179,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;
 
@@ -2190,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.
@@ -2210,16 +2564,23 @@ char **ast_cli_completion_matches(const char *text, const char *word)
                max_equal = i;
        }
 
-       if (!(retstr = ast_malloc(max_equal + 1)))
+       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;
 
@@ -2236,7 +2597,7 @@ static int more_words (const char * const *dst)
        }
        return 0;
 }
-       
+
 /*
  * generate the entry at position 'state'
  */
@@ -2311,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;
@@ -2328,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;
@@ -2355,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;
        }
 
        /*
@@ -2369,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)
@@ -2399,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;
+}