Modules: Additional improvements to CLI completion.
[asterisk/asterisk.git] / main / cli.c
index bff5869..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.
@@ -109,6 +107,9 @@ 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
 
@@ -222,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>" */
@@ -256,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;
@@ -284,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);
@@ -370,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;
@@ -446,19 +427,11 @@ static char *handle_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args
        case CLI_INIT:
                e->command = "core set debug";
                e->usage =
-#if !defined(LOW_MEMORY)
                        "Usage: core set debug [atleast] <level> [module]\n"
-#else
-                       "Usage: core set debug [atleast] <level>\n"
-#endif
                        "       core set debug off\n"
                        "\n"
-#if !defined(LOW_MEMORY)
                        "       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 messages to be displayed.\n"
-#endif
                        "       0 or off means no messages should be displayed.\n"
                        "       Equivalent to -d[d[...]] on startup\n";
                return NULL;
@@ -486,13 +459,9 @@ static char *handle_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args
                        } 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 && !atleast && strcasecmp(argv3, "off"))
+               } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off") && strcasecmp(argv3, "channel"))
                        || (a->pos == 5 && atleast)) {
-                       const char *pos = S_OR(a->argv[a->pos], "");
-
-                       return ast_complete_source_filename(pos, a->n);
-#endif
+                       return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_RUNNING);
                }
                return NULL;
        }
@@ -743,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;
@@ -772,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;
@@ -799,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)
@@ -872,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;
 }
 
@@ -892,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
@@ -909,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);
@@ -920,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;
 
@@ -927,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"
@@ -937,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 */
@@ -967,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;
@@ -1033,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)) {
@@ -1071,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);
                        }
                }
@@ -1105,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:
@@ -1118,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) {
@@ -1430,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,
        };
@@ -1442,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)) {
@@ -1521,12 +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;
-       char nativeformats[256];
        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;
-       struct ast_callid *callid;
+       ast_callid callid;
        char callid_buf[32];
+       int stream_num;
 
        switch (cmd) {
        case CLI_INIT:
@@ -1576,10 +1573,10 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
        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_callid_unref(callid);
        }
 
        ast_str_append(&output, 0,
@@ -1634,14 +1631,14 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                ast_channel_language(chan),
                ast_state2str(ast_channel_state(chan)),
                ast_channel_state(chan),
-               ast_getformatname_multiple(nativeformats, sizeof(nativeformats), ast_channel_nativeformats(chan)),
-               ast_getformatname(ast_channel_writeformat(chan)),
-               ast_getformatname(ast_channel_readformat(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),
-               ast_channel_whentohangup(chan)->tv_sec,
+               (long)ast_channel_whentohangup(chan)->tv_sec,
                cdrtime,
                bridge ? bridge->uniqueid : "(Not bridged)",
                ast_channel_context(chan),
@@ -1653,16 +1650,36 @@ static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_ar
                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_cdr_serialize_variables(ast_channel_name(chan), &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));
@@ -2021,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);
 }
 
 /*!
@@ -2199,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");
@@ -2207,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) {
@@ -2221,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;
@@ -2240,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);
@@ -2291,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;
 }
@@ -2653,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;
@@ -2670,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;
@@ -2697,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;
        }
 
        /*
@@ -2711,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)
@@ -2741,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;
+}