Sat Apr 26 2014 22:01:35

Asterisk developer's documentation


cli.c
Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Standard Command Line Interface
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  */
00025 
00026 /*** MODULEINFO
00027    <support_level>core</support_level>
00028  ***/
00029 
00030 #include "asterisk.h"
00031 
00032 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 405431 $")
00033 
00034 #include "asterisk/_private.h"
00035 #include "asterisk/paths.h"   /* use ast_config_AST_MODULE_DIR */
00036 #include <sys/signal.h>
00037 #include <signal.h>
00038 #include <ctype.h>
00039 #include <regex.h>
00040 #include <pwd.h>
00041 #include <grp.h>
00042 #include <editline/readline.h>
00043 
00044 #include "asterisk/cli.h"
00045 #include "asterisk/linkedlists.h"
00046 #include "asterisk/module.h"
00047 #include "asterisk/pbx.h"
00048 #include "asterisk/channel.h"
00049 #include "asterisk/utils.h"
00050 #include "asterisk/app.h"
00051 #include "asterisk/lock.h"
00052 #include "asterisk/threadstorage.h"
00053 #include "asterisk/translate.h"
00054 
00055 /*!
00056  * \brief List of restrictions per user.
00057  */
00058 struct cli_perm {
00059    unsigned int permit:1;           /*!< 1=Permit 0=Deny */
00060    char *command;          /*!< Command name (to apply restrictions) */
00061    AST_LIST_ENTRY(cli_perm) list;
00062 };
00063 
00064 AST_LIST_HEAD_NOLOCK(cli_perm_head, cli_perm);
00065 
00066 /*! \brief list of users to apply restrictions. */
00067 struct usergroup_cli_perm {
00068    int uid;          /*!< User ID (-1 disabled) */
00069    int gid;          /*!< Group ID (-1 disabled) */
00070    struct cli_perm_head *perms;     /*!< List of permissions. */
00071    AST_LIST_ENTRY(usergroup_cli_perm) list;/*!< List mechanics */
00072 };
00073 /*! \brief CLI permissions config file. */
00074 static const char perms_config[] = "cli_permissions.conf";
00075 /*! \brief Default permissions value 1=Permit 0=Deny */
00076 static int cli_default_perm = 1;
00077 
00078 /*! \brief mutex used to prevent a user from running the 'cli reload permissions' command while
00079  * it is already running. */
00080 AST_MUTEX_DEFINE_STATIC(permsconfiglock);
00081 /*! \brief  List of users and permissions. */
00082 static AST_RWLIST_HEAD_STATIC(cli_perms, usergroup_cli_perm);
00083 
00084 /*!
00085  * \brief map a debug or verbose level to a module name
00086  */
00087 struct module_level {
00088    unsigned int level;
00089    AST_RWLIST_ENTRY(module_level) entry;
00090    char module[0];
00091 };
00092 
00093 AST_RWLIST_HEAD(module_level_list, module_level);
00094 
00095 /*! list of module names and their debug levels */
00096 static struct module_level_list debug_modules = AST_RWLIST_HEAD_INIT_VALUE;
00097 
00098 AST_THREADSTORAGE(ast_cli_buf);
00099 
00100 /*! \brief Initial buffer size for resulting strings in ast_cli() */
00101 #define AST_CLI_INITLEN   256
00102 
00103 void ast_cli(int fd, const char *fmt, ...)
00104 {
00105    int res;
00106    struct ast_str *buf;
00107    va_list ap;
00108 
00109    if (!(buf = ast_str_thread_get(&ast_cli_buf, AST_CLI_INITLEN)))
00110       return;
00111 
00112    va_start(ap, fmt);
00113    res = ast_str_set_va(&buf, 0, fmt, ap);
00114    va_end(ap);
00115 
00116    if (res != AST_DYNSTR_BUILD_FAILED) {
00117       ast_carefulwrite(fd, ast_str_buffer(buf), ast_str_strlen(buf), 100);
00118    }
00119 }
00120 
00121 unsigned int ast_debug_get_by_module(const char *module)
00122 {
00123    struct module_level *ml;
00124    unsigned int res = 0;
00125 
00126    AST_RWLIST_RDLOCK(&debug_modules);
00127    AST_LIST_TRAVERSE(&debug_modules, ml, entry) {
00128       if (!strcasecmp(ml->module, module)) {
00129          res = ml->level;
00130          break;
00131       }
00132    }
00133    AST_RWLIST_UNLOCK(&debug_modules);
00134 
00135    return res;
00136 }
00137 
00138 unsigned int ast_verbose_get_by_module(const char *module)
00139 {
00140    return 0;
00141 }
00142 
00143 /*! \internal
00144  *  \brief Check if the user with 'uid' and 'gid' is allow to execute 'command',
00145  *    if command starts with '_' then not check permissions, just permit
00146  *    to run the 'command'.
00147  *    if uid == -1 or gid == -1 do not check permissions.
00148  *    if uid == -2 and gid == -2 is because rasterisk client didn't send
00149  *    the credentials, so the cli_default_perm will be applied.
00150  *  \param uid User ID.
00151  *  \param gid Group ID.
00152  *  \param command Command name to check permissions.
00153  *  \retval 1 if has permission
00154  *  \retval 0 if it is not allowed.
00155  */
00156 static int cli_has_permissions(int uid, int gid, const char *command)
00157 {
00158    struct usergroup_cli_perm *user_perm;
00159    struct cli_perm *perm;
00160    /* set to the default permissions general option. */
00161    int isallowg = cli_default_perm, isallowu = -1, ispattern;
00162    regex_t regexbuf;
00163 
00164    /* if uid == -1 or gid == -1 do not check permissions.
00165       if uid == -2 and gid == -2 is because rasterisk client didn't send
00166       the credentials, so the cli_default_perm will be applied. */
00167    if ((uid == CLI_NO_PERMS && gid == CLI_NO_PERMS) || command[0] == '_') {
00168       return 1;
00169    }
00170 
00171    if (gid < 0 && uid < 0) {
00172       return cli_default_perm;
00173    }
00174 
00175    AST_RWLIST_RDLOCK(&cli_perms);
00176    AST_LIST_TRAVERSE(&cli_perms, user_perm, list) {
00177       if (user_perm->gid != gid && user_perm->uid != uid) {
00178          continue;
00179       }
00180       AST_LIST_TRAVERSE(user_perm->perms, perm, list) {
00181          if (strcasecmp(perm->command, "all") && strncasecmp(perm->command, command, strlen(perm->command))) {
00182             /* if the perm->command is a pattern, check it against command. */
00183             ispattern = !regcomp(&regexbuf, perm->command, REG_EXTENDED | REG_NOSUB | REG_ICASE);
00184             if (ispattern && regexec(&regexbuf, command, 0, NULL, 0)) {
00185                regfree(&regexbuf);
00186                continue;
00187             }
00188             if (!ispattern) {
00189                continue;
00190             }
00191             regfree(&regexbuf);
00192          }
00193          if (user_perm->uid == uid) {
00194             /* this is a user definition. */
00195             isallowu = perm->permit;
00196          } else {
00197             /* otherwise is a group definition. */
00198             isallowg = perm->permit;
00199          }
00200       }
00201    }
00202    AST_RWLIST_UNLOCK(&cli_perms);
00203    if (isallowu > -1) {
00204       /* user definition override group definition. */
00205       isallowg = isallowu;
00206    }
00207 
00208    return isallowg;
00209 }
00210 
00211 static AST_RWLIST_HEAD_STATIC(helpers, ast_cli_entry);
00212 
00213 static char *complete_fn(const char *word, int state)
00214 {
00215    char *c, *d;
00216    char filename[PATH_MAX];
00217 
00218    if (word[0] == '/')
00219       ast_copy_string(filename, word, sizeof(filename));
00220    else
00221       snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
00222 
00223    c = d = filename_completion_function(filename, state);
00224 
00225    if (c && word[0] != '/')
00226       c += (strlen(ast_config_AST_MODULE_DIR) + 1);
00227    if (c)
00228       c = ast_strdup(c);
00229 
00230    free(d);
00231 
00232    return c;
00233 }
00234 
00235 static char *handle_load(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00236 {
00237    /* "module load <mod>" */
00238    switch (cmd) {
00239    case CLI_INIT:
00240       e->command = "module load";
00241       e->usage =
00242          "Usage: module load <module name>\n"
00243          "       Loads the specified module into Asterisk.\n";
00244       return NULL;
00245 
00246    case CLI_GENERATE:
00247       if (a->pos != e->args)
00248          return NULL;
00249       return complete_fn(a->word, a->n);
00250    }
00251    if (a->argc != e->args + 1)
00252       return CLI_SHOWUSAGE;
00253    if (ast_load_resource(a->argv[e->args])) {
00254       ast_cli(a->fd, "Unable to load module %s\n", a->argv[e->args]);
00255       return CLI_FAILURE;
00256    }
00257    ast_cli(a->fd, "Loaded %s\n", a->argv[e->args]);
00258    return CLI_SUCCESS;
00259 }
00260 
00261 static char *handle_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00262 {
00263    int x;
00264 
00265    switch (cmd) {
00266    case CLI_INIT:
00267       e->command = "module reload";
00268       e->usage =
00269          "Usage: module reload [module ...]\n"
00270          "       Reloads configuration files for all listed modules which support\n"
00271          "       reloading, or for all supported modules if none are listed.\n";
00272       return NULL;
00273 
00274    case CLI_GENERATE:
00275       return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 1);
00276    }
00277    if (a->argc == e->args) {
00278       ast_module_reload(NULL);
00279       return CLI_SUCCESS;
00280    }
00281    for (x = e->args; x < a->argc; x++) {
00282       int res = ast_module_reload(a->argv[x]);
00283       /* XXX reload has multiple error returns, including -1 on error and 2 on success */
00284       switch (res) {
00285       case 0:
00286          ast_cli(a->fd, "No such module '%s'\n", a->argv[x]);
00287          break;
00288       case 1:
00289          ast_cli(a->fd, "Module '%s' does not support reload\n", a->argv[x]);
00290          break;
00291       }
00292    }
00293    return CLI_SUCCESS;
00294 }
00295 
00296 static char *handle_core_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00297 {
00298    switch (cmd) {
00299    case CLI_INIT:
00300       e->command = "core reload";
00301       e->usage =
00302          "Usage: core reload\n"
00303          "       Execute a global reload.\n";
00304       return NULL;
00305 
00306    case CLI_GENERATE:
00307       return NULL;
00308    }
00309 
00310    if (a->argc != e->args) {
00311       return CLI_SHOWUSAGE;
00312    }
00313 
00314    ast_module_reload(NULL);
00315 
00316    return CLI_SUCCESS;
00317 }
00318 
00319 /*!
00320  * \brief Find the module level setting
00321  *
00322  * \param module Module name to look for.
00323  * \param mll List to search.
00324  *
00325  * \retval level struct found on success.
00326  * \retval NULL not found.
00327  */
00328 static struct module_level *find_module_level(const char *module, struct module_level_list *mll)
00329 {
00330    struct module_level *ml;
00331 
00332    AST_LIST_TRAVERSE(mll, ml, entry) {
00333       if (!strcasecmp(ml->module, module))
00334          return ml;
00335    }
00336 
00337    return NULL;
00338 }
00339 
00340 static char *complete_number(const char *partial, unsigned int min, unsigned int max, int n)
00341 {
00342    int i, count = 0;
00343    unsigned int prospective[2];
00344    unsigned int part = strtoul(partial, NULL, 10);
00345    char next[12];
00346 
00347    if (part < min || part > max) {
00348       return NULL;
00349    }
00350 
00351    for (i = 0; i < 21; i++) {
00352       if (i == 0) {
00353          prospective[0] = prospective[1] = part;
00354       } else if (part == 0 && !ast_strlen_zero(partial)) {
00355          break;
00356       } else if (i < 11) {
00357          prospective[0] = prospective[1] = part * 10 + (i - 1);
00358       } else {
00359          prospective[0] = (part * 10 + (i - 11)) * 10;
00360          prospective[1] = prospective[0] + 9;
00361       }
00362       if (i < 11 && (prospective[0] < min || prospective[0] > max)) {
00363          continue;
00364       } else if (prospective[1] < min || prospective[0] > max) {
00365          continue;
00366       }
00367 
00368       if (++count > n) {
00369          if (i < 11) {
00370             snprintf(next, sizeof(next), "%u", prospective[0]);
00371          } else {
00372             snprintf(next, sizeof(next), "%u...", prospective[0] / 10);
00373          }
00374          return ast_strdup(next);
00375       }
00376    }
00377    return NULL;
00378 }
00379 
00380 static void status_debug_verbose(struct ast_cli_args *a, const char *what, int old_val, int cur_val)
00381 {
00382    char was_buf[30];
00383    const char *was;
00384 
00385    if (old_val) {
00386       snprintf(was_buf, sizeof(was_buf), "%d", old_val);
00387       was = was_buf;
00388    } else {
00389       was = "OFF";
00390    }
00391 
00392    if (old_val == cur_val) {
00393       ast_cli(a->fd, "%s is still %s.\n", what, was);
00394    } else {
00395       char now_buf[30];
00396       const char *now;
00397 
00398       if (cur_val) {
00399          snprintf(now_buf, sizeof(now_buf), "%d", cur_val);
00400          now = now_buf;
00401       } else {
00402          now = "OFF";
00403       }
00404 
00405       ast_cli(a->fd, "%s was %s and is now %s.\n", what, was, now);
00406    }
00407 }
00408 
00409 static char *handle_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00410 {
00411    int oldval;
00412    int newlevel;
00413    int atleast = 0;
00414    const char *argv3 = a->argv ? S_OR(a->argv[3], "") : "";
00415    struct module_level *ml;
00416 
00417    switch (cmd) {
00418    case CLI_INIT:
00419       e->command = "core set debug";
00420       e->usage =
00421 #if !defined(LOW_MEMORY)
00422          "Usage: core set debug [atleast] <level> [module]\n"
00423 #else
00424          "Usage: core set debug [atleast] <level>\n"
00425 #endif
00426          "       core set debug off\n"
00427          "\n"
00428 #if !defined(LOW_MEMORY)
00429          "       Sets level of debug messages to be displayed or\n"
00430          "       sets a module name to display debug messages from.\n"
00431 #else
00432          "       Sets level of debug messages to be displayed.\n"
00433 #endif
00434          "       0 or off means no messages should be displayed.\n"
00435          "       Equivalent to -d[d[...]] on startup\n";
00436       return NULL;
00437 
00438    case CLI_GENERATE:
00439       if (!strcasecmp(argv3, "atleast")) {
00440          atleast = 1;
00441       }
00442       if (a->pos == 3 || (a->pos == 4 && atleast)) {
00443          const char *pos = a->pos == 3 ? argv3 : S_OR(a->argv[4], "");
00444          int numbermatch = (ast_strlen_zero(pos) || strchr("123456789", pos[0])) ? 0 : 21;
00445 
00446          if (a->n < 21 && numbermatch == 0) {
00447             return complete_number(pos, 0, 0x7fffffff, a->n);
00448          } else if (pos[0] == '0') {
00449             if (a->n == 0) {
00450                return ast_strdup("0");
00451             }
00452          } else if (a->n == (21 - numbermatch)) {
00453             if (a->pos == 3 && !strncasecmp(argv3, "off", strlen(argv3))) {
00454                return ast_strdup("off");
00455             } else if (a->pos == 3 && !strncasecmp(argv3, "atleast", strlen(argv3))) {
00456                return ast_strdup("atleast");
00457             }
00458          } else if (a->n == (22 - numbermatch) && a->pos == 3 && ast_strlen_zero(argv3)) {
00459             return ast_strdup("atleast");
00460          }
00461 #if !defined(LOW_MEMORY)
00462       } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off"))
00463          || (a->pos == 5 && atleast)) {
00464          const char *pos = S_OR(a->argv[a->pos], "");
00465 
00466          return ast_complete_source_filename(pos, a->n);
00467 #endif
00468       }
00469       return NULL;
00470    }
00471    /* all the above return, so we proceed with the handler.
00472     * we are guaranteed to be called with argc >= e->args;
00473     */
00474 
00475    if (a->argc <= e->args) {
00476       return CLI_SHOWUSAGE;
00477    }
00478 
00479    if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args], "off")) {
00480       newlevel = 0;
00481    } else {
00482       if (!strcasecmp(a->argv[e->args], "atleast")) {
00483          atleast = 1;
00484       }
00485       if (a->argc != e->args + atleast + 1 && a->argc != e->args + atleast + 2) {
00486          return CLI_SHOWUSAGE;
00487       }
00488       if (sscanf(a->argv[e->args + atleast], "%30d", &newlevel) != 1) {
00489          return CLI_SHOWUSAGE;
00490       }
00491 
00492       if (a->argc == e->args + atleast + 2) {
00493          /* We have specified a module name. */
00494          char *mod = ast_strdupa(a->argv[e->args + atleast + 1]);
00495          int mod_len = strlen(mod);
00496 
00497          if (3 < mod_len && !strcasecmp(mod + mod_len - 3, ".so")) {
00498             mod[mod_len - 3] = '\0';
00499          }
00500 
00501          AST_RWLIST_WRLOCK(&debug_modules);
00502 
00503          ml = find_module_level(mod, &debug_modules);
00504          if (!newlevel) {
00505             if (!ml) {
00506                /* Specified off for a nonexistent entry. */
00507                AST_RWLIST_UNLOCK(&debug_modules);
00508                ast_cli(a->fd, "Core debug is still 0 for '%s'.\n", mod);
00509                return CLI_SUCCESS;
00510             }
00511             AST_RWLIST_REMOVE(&debug_modules, ml, entry);
00512             if (AST_RWLIST_EMPTY(&debug_modules)) {
00513                ast_clear_flag(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
00514             }
00515             AST_RWLIST_UNLOCK(&debug_modules);
00516             ast_cli(a->fd, "Core debug was %d and has been set to 0 for '%s'.\n",
00517                ml->level, mod);
00518             ast_free(ml);
00519             return CLI_SUCCESS;
00520          }
00521 
00522          if (ml) {
00523             if ((atleast && newlevel < ml->level) || ml->level == newlevel) {
00524                ast_cli(a->fd, "Core debug is still %d for '%s'.\n", ml->level, mod);
00525                AST_RWLIST_UNLOCK(&debug_modules);
00526                return CLI_SUCCESS;
00527             }
00528             oldval = ml->level;
00529             ml->level = newlevel;
00530          } else {
00531             ml = ast_calloc(1, sizeof(*ml) + strlen(mod) + 1);
00532             if (!ml) {
00533                AST_RWLIST_UNLOCK(&debug_modules);
00534                return CLI_FAILURE;
00535             }
00536             oldval = ml->level;
00537             ml->level = newlevel;
00538             strcpy(ml->module, mod);
00539             AST_RWLIST_INSERT_TAIL(&debug_modules, ml, entry);
00540          }
00541          ast_set_flag(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
00542 
00543          ast_cli(a->fd, "Core debug was %d and has been set to %d for '%s'.\n",
00544             oldval, ml->level, ml->module);
00545 
00546          AST_RWLIST_UNLOCK(&debug_modules);
00547 
00548          return CLI_SUCCESS;
00549       }
00550    }
00551 
00552    /* Update global debug level */
00553    if (!newlevel) {
00554       /* Specified level was 0 or off. */
00555       AST_RWLIST_WRLOCK(&debug_modules);
00556       while ((ml = AST_RWLIST_REMOVE_HEAD(&debug_modules, entry))) {
00557          ast_free(ml);
00558       }
00559       ast_clear_flag(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
00560       AST_RWLIST_UNLOCK(&debug_modules);
00561    }
00562    oldval = option_debug;
00563    if (!atleast || newlevel > option_debug) {
00564       option_debug = newlevel;
00565    }
00566 
00567    /* Report debug level status */
00568    status_debug_verbose(a, "Core debug", oldval, option_debug);
00569 
00570    return CLI_SUCCESS;
00571 }
00572 
00573 static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00574 {
00575    int oldval;
00576    int newlevel;
00577    int atleast = 0;
00578    int silent = 0;
00579    const char *argv3 = a->argv ? S_OR(a->argv[3], "") : "";
00580 
00581    switch (cmd) {
00582    case CLI_INIT:
00583       e->command = "core set verbose";
00584       e->usage =
00585          "Usage: core set verbose [atleast] <level> [silent]\n"
00586          "       core set verbose off\n"
00587          "\n"
00588          "       Sets level of verbose messages to be displayed.\n"
00589          "       0 or off means no verbose messages should be displayed.\n"
00590          "       The silent option means the command does not report what\n"
00591          "       happened to the verbose level.\n"
00592          "       Equivalent to -v[v[...]] on startup\n";
00593       return NULL;
00594 
00595    case CLI_GENERATE:
00596       if (!strcasecmp(argv3, "atleast")) {
00597          atleast = 1;
00598       }
00599       if (a->pos == 3 || (a->pos == 4 && atleast)) {
00600          const char *pos = a->pos == 3 ? argv3 : S_OR(a->argv[4], "");
00601          int numbermatch = (ast_strlen_zero(pos) || strchr("123456789", pos[0])) ? 0 : 21;
00602 
00603          if (a->n < 21 && numbermatch == 0) {
00604             return complete_number(pos, 0, 0x7fffffff, a->n);
00605          } else if (pos[0] == '0') {
00606             if (a->n == 0) {
00607                return ast_strdup("0");
00608             }
00609          } else if (a->n == (21 - numbermatch)) {
00610             if (a->pos == 3 && !strncasecmp(argv3, "off", strlen(argv3))) {
00611                return ast_strdup("off");
00612             } else if (a->pos == 3 && !strncasecmp(argv3, "atleast", strlen(argv3))) {
00613                return ast_strdup("atleast");
00614             }
00615          } else if (a->n == (22 - numbermatch) && a->pos == 3 && ast_strlen_zero(argv3)) {
00616             return ast_strdup("atleast");
00617          }
00618       } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off"))
00619          || (a->pos == 5 && atleast)) {
00620          const char *pos = S_OR(a->argv[a->pos], "");
00621 
00622          if (a->n == 0 && !strncasecmp(pos, "silent", strlen(pos))) {
00623             return ast_strdup("silent");
00624          }
00625       }
00626       return NULL;
00627    }
00628    /* all the above return, so we proceed with the handler.
00629     * we are guaranteed to be called with argc >= e->args;
00630     */
00631 
00632    if (a->argc <= e->args) {
00633       return CLI_SHOWUSAGE;
00634    }
00635 
00636    if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args], "off")) {
00637       newlevel = 0;
00638    } else {
00639       if (!strcasecmp(a->argv[e->args], "atleast")) {
00640          atleast = 1;
00641       }
00642       if (a->argc == e->args + atleast + 2
00643          && !strcasecmp(a->argv[e->args + atleast + 1], "silent")) {
00644          silent = 1;
00645       }
00646       if (a->argc != e->args + atleast + silent + 1) {
00647          return CLI_SHOWUSAGE;
00648       }
00649       if (sscanf(a->argv[e->args + atleast], "%30d", &newlevel) != 1) {
00650          return CLI_SHOWUSAGE;
00651       }
00652    }
00653 
00654    /* Update verbose level */
00655    oldval = ast_verb_console_get();
00656    if (!atleast || newlevel > oldval) {
00657       ast_verb_console_set(newlevel);
00658    } else {
00659       newlevel = oldval;
00660    }
00661 
00662    if (silent) {
00663       /* Be silent after setting the level. */
00664       return CLI_SUCCESS;
00665    }
00666 
00667    /* Report verbose level status */
00668    status_debug_verbose(a, "Console verbose", oldval, newlevel);
00669 
00670    return CLI_SUCCESS;
00671 }
00672 
00673 static char *handle_logger_mute(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00674 {
00675    switch (cmd) {
00676    case CLI_INIT:
00677       e->command = "logger mute";
00678       e->usage =
00679          "Usage: logger mute\n"
00680          "       Disables logging output to the current console, making it possible to\n"
00681          "       gather information without being disturbed by scrolling lines.\n";
00682       return NULL;
00683    case CLI_GENERATE:
00684       return NULL;
00685    }
00686 
00687    if (a->argc < 2 || a->argc > 3)
00688       return CLI_SHOWUSAGE;
00689 
00690    if (a->argc == 3 && !strcasecmp(a->argv[2], "silent"))
00691       ast_console_toggle_mute(a->fd, 1);
00692    else
00693       ast_console_toggle_mute(a->fd, 0);
00694 
00695    return CLI_SUCCESS;
00696 }
00697 
00698 static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00699 {
00700    /* "module unload mod_1 [mod_2 .. mod_N]" */
00701    int x;
00702    int force = AST_FORCE_SOFT;
00703    const char *s;
00704 
00705    switch (cmd) {
00706    case CLI_INIT:
00707       e->command = "module unload";
00708       e->usage =
00709          "Usage: module unload [-f|-h] <module_1> [<module_2> ... ]\n"
00710          "       Unloads the specified module from Asterisk. The -f\n"
00711          "       option causes the module to be unloaded even if it is\n"
00712          "       in use (may cause a crash) and the -h module causes the\n"
00713          "       module to be unloaded even if the module says it cannot, \n"
00714          "       which almost always will cause a crash.\n";
00715       return NULL;
00716 
00717    case CLI_GENERATE:
00718       return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
00719    }
00720    if (a->argc < e->args + 1)
00721       return CLI_SHOWUSAGE;
00722    x = e->args;   /* first argument */
00723    s = a->argv[x];
00724    if (s[0] == '-') {
00725       if (s[1] == 'f')
00726          force = AST_FORCE_FIRM;
00727       else if (s[1] == 'h')
00728          force = AST_FORCE_HARD;
00729       else
00730          return CLI_SHOWUSAGE;
00731       if (a->argc < e->args + 2) /* need at least one module name */
00732          return CLI_SHOWUSAGE;
00733       x++;  /* skip this argument */
00734    }
00735 
00736    for (; x < a->argc; x++) {
00737       if (ast_unload_resource(a->argv[x], force)) {
00738          ast_cli(a->fd, "Unable to unload resource %s\n", a->argv[x]);
00739          return CLI_FAILURE;
00740       }
00741       ast_cli(a->fd, "Unloaded %s\n", a->argv[x]);
00742    }
00743 
00744    return CLI_SUCCESS;
00745 }
00746 
00747 #define MODLIST_FORMAT  "%-30s %-40.40s %-10d\n"
00748 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
00749 
00750 AST_MUTEX_DEFINE_STATIC(climodentrylock);
00751 static int climodentryfd = -1;
00752 
00753 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
00754 {
00755    /* Comparing the like with the module */
00756    if (strcasestr(module, like) ) {
00757       ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
00758       return 1;
00759    }
00760    return 0;
00761 }
00762 
00763 static void print_uptimestr(int fd, struct timeval timeval, const char *prefix, int printsec)
00764 {
00765    int x; /* the main part - years, weeks, etc. */
00766    struct ast_str *out;
00767 
00768 #define SECOND (1)
00769 #define MINUTE (SECOND*60)
00770 #define HOUR (MINUTE*60)
00771 #define DAY (HOUR*24)
00772 #define WEEK (DAY*7)
00773 #define YEAR (DAY*365)
00774 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
00775    if (timeval.tv_sec < 0) /* invalid, nothing to show */
00776       return;
00777 
00778    if (printsec)  {  /* plain seconds output */
00779       ast_cli(fd, "%s: %lu\n", prefix, (u_long)timeval.tv_sec);
00780       return;
00781    }
00782    out = ast_str_alloca(256);
00783    if (timeval.tv_sec > YEAR) {
00784       x = (timeval.tv_sec / YEAR);
00785       timeval.tv_sec -= (x * YEAR);
00786       ast_str_append(&out, 0, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
00787    }
00788    if (timeval.tv_sec > WEEK) {
00789       x = (timeval.tv_sec / WEEK);
00790       timeval.tv_sec -= (x * WEEK);
00791       ast_str_append(&out, 0, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
00792    }
00793    if (timeval.tv_sec > DAY) {
00794       x = (timeval.tv_sec / DAY);
00795       timeval.tv_sec -= (x * DAY);
00796       ast_str_append(&out, 0, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
00797    }
00798    if (timeval.tv_sec > HOUR) {
00799       x = (timeval.tv_sec / HOUR);
00800       timeval.tv_sec -= (x * HOUR);
00801       ast_str_append(&out, 0, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
00802    }
00803    if (timeval.tv_sec > MINUTE) {
00804       x = (timeval.tv_sec / MINUTE);
00805       timeval.tv_sec -= (x * MINUTE);
00806       ast_str_append(&out, 0, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
00807    }
00808    x = timeval.tv_sec;
00809    if (x > 0 || ast_str_strlen(out) == 0) /* if there is nothing, print 0 seconds */
00810       ast_str_append(&out, 0, "%d second%s ", x, ESS(x));
00811    ast_cli(fd, "%s: %s\n", prefix, ast_str_buffer(out));
00812 }
00813 
00814 static struct ast_cli_entry *cli_next(struct ast_cli_entry *e)
00815 {
00816    if (e) {
00817       return AST_LIST_NEXT(e, list);
00818    } else {
00819       return AST_LIST_FIRST(&helpers);
00820    }
00821 }
00822 
00823 static char * handle_showuptime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00824 {
00825    struct timeval curtime = ast_tvnow();
00826    int printsec;
00827 
00828    switch (cmd) {
00829    case CLI_INIT:
00830       e->command = "core show uptime [seconds]";
00831       e->usage =
00832          "Usage: core show uptime [seconds]\n"
00833          "       Shows Asterisk uptime information.\n"
00834          "       The seconds word returns the uptime in seconds only.\n";
00835       return NULL;
00836 
00837    case CLI_GENERATE:
00838       return NULL;
00839    }
00840    /* regular handler */
00841    if (a->argc == e->args && !strcasecmp(a->argv[e->args-1],"seconds"))
00842       printsec = 1;
00843    else if (a->argc == e->args-1)
00844       printsec = 0;
00845    else
00846       return CLI_SHOWUSAGE;
00847    if (ast_startuptime.tv_sec)
00848       print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
00849    if (ast_lastreloadtime.tv_sec)
00850       print_uptimestr(a->fd, ast_tvsub(curtime, ast_lastreloadtime), "Last reload", printsec);
00851    return CLI_SUCCESS;
00852 }
00853 
00854 static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00855 {
00856    const char *like;
00857 
00858    switch (cmd) {
00859    case CLI_INIT:
00860       e->command = "module show [like]";
00861       e->usage =
00862          "Usage: module show [like keyword]\n"
00863          "       Shows Asterisk modules currently in use, and usage statistics.\n";
00864       return NULL;
00865 
00866    case CLI_GENERATE:
00867       if (a->pos == e->args)
00868          return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
00869       else
00870          return NULL;
00871    }
00872    /* all the above return, so we proceed with the handler.
00873     * we are guaranteed to have argc >= e->args
00874     */
00875    if (a->argc == e->args - 1)
00876       like = "";
00877    else if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args-1], "like") )
00878       like = a->argv[e->args];
00879    else
00880       return CLI_SHOWUSAGE;
00881 
00882    ast_mutex_lock(&climodentrylock);
00883    climodentryfd = a->fd; /* global, protected by climodentrylock */
00884    ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
00885    ast_cli(a->fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
00886    climodentryfd = -1;
00887    ast_mutex_unlock(&climodentrylock);
00888    return CLI_SUCCESS;
00889 }
00890 #undef MODLIST_FORMAT
00891 #undef MODLIST_FORMAT2
00892 
00893 static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00894 {
00895    struct timeval curtime = ast_tvnow();
00896    int showuptime, printsec;
00897 
00898    switch (cmd) {
00899    case CLI_INIT:
00900       e->command = "core show calls [uptime]";
00901       e->usage =
00902          "Usage: core show calls [uptime] [seconds]\n"
00903          "       Lists number of currently active calls and total number of calls\n"
00904          "       processed through PBX since last restart. If 'uptime' is specified\n"
00905          "       the system uptime is also displayed. If 'seconds' is specified in\n"
00906          "       addition to 'uptime', the system uptime is displayed in seconds.\n";
00907       return NULL;
00908 
00909    case CLI_GENERATE:
00910       if (a->pos != e->args)
00911          return NULL;
00912       return a->n == 0  ? ast_strdup("seconds") : NULL;
00913    }
00914 
00915    /* regular handler */
00916    if (a->argc >= e->args && !strcasecmp(a->argv[e->args-1],"uptime")) {
00917       showuptime = 1;
00918 
00919       if (a->argc == e->args+1 && !strcasecmp(a->argv[e->args],"seconds"))
00920          printsec = 1;
00921       else if (a->argc == e->args)
00922          printsec = 0;
00923       else
00924          return CLI_SHOWUSAGE;
00925    } else if (a->argc == e->args-1) {
00926       showuptime = 0;
00927       printsec = 0;
00928    } else
00929       return CLI_SHOWUSAGE;
00930 
00931    if (option_maxcalls) {
00932       ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
00933          ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
00934          ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
00935    } else {
00936       ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
00937    }
00938 
00939    ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
00940 
00941    if (ast_startuptime.tv_sec && showuptime) {
00942       print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
00943    }
00944 
00945    return RESULT_SUCCESS;
00946 }
00947 
00948 static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00949 {
00950 #define FORMAT_STRING  "%-20.20s %-20.20s %-7.7s %-30.30s\n"
00951 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
00952 #define CONCISE_FORMAT_STRING  "%s!%s!%s!%d!%s!%s!%s!%s!%s!%s!%d!%s!%s!%s\n"
00953 #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"
00954 #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"
00955 
00956    struct ast_channel *c = NULL;
00957    int numchans = 0, concise = 0, verbose = 0, count = 0;
00958    struct ast_channel_iterator *iter = NULL;
00959 
00960    switch (cmd) {
00961    case CLI_INIT:
00962       e->command = "core show channels [concise|verbose|count]";
00963       e->usage =
00964          "Usage: core show channels [concise|verbose|count]\n"
00965          "       Lists currently defined channels and some information about them. If\n"
00966          "       'concise' is specified, the format is abridged and in a more easily\n"
00967          "       machine parsable format. If 'verbose' is specified, the output includes\n"
00968          "       more and longer fields. If 'count' is specified only the channel and call\n"
00969          "       count is output.\n"
00970          "  The 'concise' option is deprecated and will be removed from future versions\n"
00971          "  of Asterisk.\n";
00972       return NULL;
00973 
00974    case CLI_GENERATE:
00975       return NULL;
00976    }
00977 
00978    if (a->argc == e->args) {
00979       if (!strcasecmp(a->argv[e->args-1],"concise"))
00980          concise = 1;
00981       else if (!strcasecmp(a->argv[e->args-1],"verbose"))
00982          verbose = 1;
00983       else if (!strcasecmp(a->argv[e->args-1],"count"))
00984          count = 1;
00985       else
00986          return CLI_SHOWUSAGE;
00987    } else if (a->argc != e->args - 1)
00988       return CLI_SHOWUSAGE;
00989 
00990    if (!count) {
00991       if (!concise && !verbose)
00992          ast_cli(a->fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
00993       else if (verbose)
00994          ast_cli(a->fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
00995             "CallerID", "Duration", "Accountcode", "PeerAccount", "BridgedTo");
00996    }
00997 
00998    if (!count && !(iter = ast_channel_iterator_all_new())) {
00999       return CLI_FAILURE;
01000    }
01001 
01002    for (; iter && (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
01003       struct ast_channel *bc;
01004       char durbuf[10] = "-";
01005 
01006       ast_channel_lock(c);
01007 
01008       bc = ast_bridged_channel(c);
01009 
01010       if (!count) {
01011          if ((concise || verbose)  && ast_channel_cdr(c) && !ast_tvzero(ast_channel_cdr(c)->start)) {
01012             int duration = (int)(ast_tvdiff_ms(ast_tvnow(), ast_channel_cdr(c)->start) / 1000);
01013             if (verbose) {
01014                int durh = duration / 3600;
01015                int durm = (duration % 3600) / 60;
01016                int durs = duration % 60;
01017                snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
01018             } else {
01019                snprintf(durbuf, sizeof(durbuf), "%d", duration);
01020             }
01021          }
01022          if (concise) {
01023             ast_cli(a->fd, CONCISE_FORMAT_STRING, ast_channel_name(c), ast_channel_context(c), ast_channel_exten(c), ast_channel_priority(c), ast_state2str(ast_channel_state(c)),
01024                ast_channel_appl(c) ? ast_channel_appl(c) : "(None)",
01025                S_OR(ast_channel_data(c), ""),   /* XXX different from verbose ? */
01026                S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, ""),
01027                S_OR(ast_channel_accountcode(c), ""),
01028                S_OR(ast_channel_peeraccount(c), ""),
01029                ast_channel_amaflags(c),
01030                durbuf,
01031                bc ? ast_channel_name(bc) : "(None)",
01032                ast_channel_uniqueid(c));
01033          } else if (verbose) {
01034             ast_cli(a->fd, VERBOSE_FORMAT_STRING, ast_channel_name(c), ast_channel_context(c), ast_channel_exten(c), ast_channel_priority(c), ast_state2str(ast_channel_state(c)),
01035                ast_channel_appl(c) ? ast_channel_appl(c) : "(None)",
01036                ast_channel_data(c) ? S_OR(ast_channel_data(c), "(Empty)" ): "(None)",
01037                S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, ""),
01038                durbuf,
01039                S_OR(ast_channel_accountcode(c), ""),
01040                S_OR(ast_channel_peeraccount(c), ""),
01041                bc ? ast_channel_name(bc) : "(None)");
01042          } else {
01043             char locbuf[40] = "(None)";
01044             char appdata[40] = "(None)";
01045 
01046             if (!ast_strlen_zero(ast_channel_context(c)) && !ast_strlen_zero(ast_channel_exten(c)))
01047                snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", ast_channel_exten(c), ast_channel_context(c), ast_channel_priority(c));
01048             if (ast_channel_appl(c))
01049                snprintf(appdata, sizeof(appdata), "%s(%s)", ast_channel_appl(c), S_OR(ast_channel_data(c), ""));
01050             ast_cli(a->fd, FORMAT_STRING, ast_channel_name(c), locbuf, ast_state2str(ast_channel_state(c)), appdata);
01051          }
01052       }
01053       ast_channel_unlock(c);
01054    }
01055 
01056    if (iter) {
01057       ast_channel_iterator_destroy(iter);
01058    }
01059 
01060    if (!concise) {
01061       numchans = ast_active_channels();
01062       ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
01063       if (option_maxcalls)
01064          ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
01065             ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
01066             ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
01067       else
01068          ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
01069 
01070       ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
01071    }
01072 
01073    return CLI_SUCCESS;
01074 
01075 #undef FORMAT_STRING
01076 #undef FORMAT_STRING2
01077 #undef CONCISE_FORMAT_STRING
01078 #undef VERBOSE_FORMAT_STRING
01079 #undef VERBOSE_FORMAT_STRING2
01080 }
01081 
01082 static char *handle_softhangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01083 {
01084    struct ast_channel *c=NULL;
01085 
01086    switch (cmd) {
01087    case CLI_INIT:
01088       e->command = "channel request hangup";
01089       e->usage =
01090          "Usage: channel request hangup <channel>|<all>\n"
01091          "       Request that a channel be hung up. The hangup takes effect\n"
01092          "       the next time the driver reads or writes from the channel.\n"
01093          "       If 'all' is specified instead of a channel name, all channels\n"
01094          "       will see the hangup request.\n";
01095       return NULL;
01096    case CLI_GENERATE:
01097       return ast_complete_channels(a->line, a->word, a->pos, a->n, e->args);
01098    }
01099 
01100    if (a->argc != 4) {
01101       return CLI_SHOWUSAGE;
01102    }
01103 
01104    if (!strcasecmp(a->argv[3], "all")) {
01105       struct ast_channel_iterator *iter = NULL;
01106       if (!(iter = ast_channel_iterator_all_new())) {
01107          return CLI_FAILURE;
01108       }
01109       for (; iter && (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
01110          ast_channel_lock(c);
01111          ast_cli(a->fd, "Requested Hangup on channel '%s'\n", ast_channel_name(c));
01112          ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
01113          ast_channel_unlock(c);
01114       }
01115       ast_channel_iterator_destroy(iter);
01116    } else if ((c = ast_channel_get_by_name(a->argv[3]))) {
01117       ast_channel_lock(c);
01118       ast_cli(a->fd, "Requested Hangup on channel '%s'\n", ast_channel_name(c));
01119       ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
01120       ast_channel_unlock(c);
01121       c = ast_channel_unref(c);
01122    } else {
01123       ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
01124    }
01125 
01126    return CLI_SUCCESS;
01127 }
01128 
01129 /*! \brief handles CLI command 'cli show permissions' */
01130 static char *handle_cli_show_permissions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01131 {
01132    struct usergroup_cli_perm *cp;
01133    struct cli_perm *perm;
01134    struct passwd *pw = NULL;
01135    struct group *gr = NULL;
01136 
01137    switch (cmd) {
01138    case CLI_INIT:
01139       e->command = "cli show permissions";
01140       e->usage =
01141          "Usage: cli show permissions\n"
01142          "       Shows CLI configured permissions.\n";
01143       return NULL;
01144    case CLI_GENERATE:
01145       return NULL;
01146    }
01147 
01148    AST_RWLIST_RDLOCK(&cli_perms);
01149    AST_LIST_TRAVERSE(&cli_perms, cp, list) {
01150       if (cp->uid >= 0) {
01151          pw = getpwuid(cp->uid);
01152          if (pw) {
01153             ast_cli(a->fd, "user: %s [uid=%d]\n", pw->pw_name, cp->uid);
01154          }
01155       } else {
01156          gr = getgrgid(cp->gid);
01157          if (gr) {
01158             ast_cli(a->fd, "group: %s [gid=%d]\n", gr->gr_name, cp->gid);
01159          }
01160       }
01161       ast_cli(a->fd, "Permissions:\n");
01162       if (cp->perms) {
01163          AST_LIST_TRAVERSE(cp->perms, perm, list) {
01164             ast_cli(a->fd, "\t%s -> %s\n", perm->permit ? "permit" : "deny", perm->command);
01165          }
01166       }
01167       ast_cli(a->fd, "\n");
01168    }
01169    AST_RWLIST_UNLOCK(&cli_perms);
01170 
01171    return CLI_SUCCESS;
01172 }
01173 
01174 /*! \brief handles CLI command 'cli reload permissions' */
01175 static char *handle_cli_reload_permissions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01176 {
01177    switch (cmd) {
01178    case CLI_INIT:
01179       e->command = "cli reload permissions";
01180       e->usage =
01181          "Usage: cli reload permissions\n"
01182          "       Reload the 'cli_permissions.conf' file.\n";
01183       return NULL;
01184    case CLI_GENERATE:
01185       return NULL;
01186    }
01187 
01188    ast_cli_perms_init(1);
01189 
01190    return CLI_SUCCESS;
01191 }
01192 
01193 /*! \brief handles CLI command 'cli check permissions' */
01194 static char *handle_cli_check_permissions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01195 {
01196    struct passwd *pw = NULL;
01197    struct group *gr;
01198    int gid = -1, uid = -1;
01199    char command[AST_MAX_ARGS] = "";
01200    struct ast_cli_entry *ce = NULL;
01201    int found = 0;
01202    char *group, *tmp;
01203 
01204    switch (cmd) {
01205    case CLI_INIT:
01206       e->command = "cli check permissions";
01207       e->usage =
01208          "Usage: cli check permissions {<username>|@<groupname>|<username>@<groupname>} [<command>]\n"
01209          "       Check permissions config for a user@group or list the allowed commands for the specified user.\n"
01210          "       The username or the groupname may be omitted.\n";
01211       return NULL;
01212    case CLI_GENERATE:
01213       if (a->pos >= 4) {
01214          return ast_cli_generator(a->line + strlen("cli check permissions") + strlen(a->argv[3]) + 1, a->word, a->n);
01215       }
01216       return NULL;
01217    }
01218 
01219    if (a->argc < 4) {
01220       return CLI_SHOWUSAGE;
01221    }
01222 
01223    tmp = ast_strdupa(a->argv[3]);
01224    group = strchr(tmp, '@');
01225    if (group) {
01226       gr = getgrnam(&group[1]);
01227       if (!gr) {
01228          ast_cli(a->fd, "Unknown group '%s'\n", &group[1]);
01229          return CLI_FAILURE;
01230       }
01231       group[0] = '\0';
01232       gid = gr->gr_gid;
01233    }
01234 
01235    if (!group && ast_strlen_zero(tmp)) {
01236       ast_cli(a->fd, "You didn't supply a username\n");
01237    } else if (!ast_strlen_zero(tmp) && !(pw = getpwnam(tmp))) {
01238       ast_cli(a->fd, "Unknown user '%s'\n", tmp);
01239       return CLI_FAILURE;
01240    } else if (pw) {
01241       uid = pw->pw_uid;
01242    }
01243 
01244    if (a->argc == 4) {
01245       while ((ce = cli_next(ce))) {
01246          /* Hide commands that start with '_' */
01247          if (ce->_full_cmd[0] == '_') {
01248             continue;
01249          }
01250          if (cli_has_permissions(uid, gid, ce->_full_cmd)) {
01251             ast_cli(a->fd, "%30.30s %s\n", ce->_full_cmd, S_OR(ce->summary, "<no description available>"));
01252             found++;
01253          }
01254       }
01255       if (!found) {
01256          ast_cli(a->fd, "You are not allowed to run any command on Asterisk\n");
01257       }
01258    } else {
01259       ast_join(command, sizeof(command), a->argv + 4);
01260       ast_cli(a->fd, "%s '%s%s%s' is %s to run command: '%s'\n", uid >= 0 ? "User" : "Group", tmp,
01261          group && uid >= 0 ? "@" : "",
01262          group ? &group[1] : "",
01263          cli_has_permissions(uid, gid, command) ? "allowed" : "not allowed", command);
01264    }
01265 
01266    return CLI_SUCCESS;
01267 }
01268 
01269 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
01270 
01271 static char *handle_commandmatchesarray(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01272 {
01273    char *buf, *obuf;
01274    int buflen = 2048;
01275    int len = 0;
01276    char **matches;
01277    int x, matchlen;
01278 
01279    switch (cmd) {
01280    case CLI_INIT:
01281       e->command = "_command matchesarray";
01282       e->usage =
01283          "Usage: _command matchesarray \"<line>\" text \n"
01284          "       This function is used internally to help with command completion and should.\n"
01285          "       never be called by the user directly.\n";
01286       return NULL;
01287    case CLI_GENERATE:
01288       return NULL;
01289    }
01290 
01291    if (a->argc != 4)
01292       return CLI_SHOWUSAGE;
01293    if (!(buf = ast_malloc(buflen)))
01294       return CLI_FAILURE;
01295    buf[len] = '\0';
01296    matches = ast_cli_completion_matches(a->argv[2], a->argv[3]);
01297    if (matches) {
01298       for (x=0; matches[x]; x++) {
01299          matchlen = strlen(matches[x]) + 1;
01300          if (len + matchlen >= buflen) {
01301             buflen += matchlen * 3;
01302             obuf = buf;
01303             if (!(buf = ast_realloc(obuf, buflen)))
01304                /* Memory allocation failure...  Just free old buffer and be done */
01305                ast_free(obuf);
01306          }
01307          if (buf)
01308             len += sprintf( buf + len, "%s ", matches[x]);
01309          ast_free(matches[x]);
01310          matches[x] = NULL;
01311       }
01312       ast_free(matches);
01313    }
01314 
01315    if (buf) {
01316       ast_cli(a->fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
01317       ast_free(buf);
01318    } else
01319       ast_cli(a->fd, "NULL\n");
01320 
01321    return CLI_SUCCESS;
01322 }
01323 
01324 
01325 
01326 static char *handle_commandnummatches(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01327 {
01328    int matches = 0;
01329 
01330    switch (cmd) {
01331    case CLI_INIT:
01332       e->command = "_command nummatches";
01333       e->usage =
01334          "Usage: _command nummatches \"<line>\" text \n"
01335          "       This function is used internally to help with command completion and should.\n"
01336          "       never be called by the user directly.\n";
01337       return NULL;
01338    case CLI_GENERATE:
01339       return NULL;
01340    }
01341 
01342    if (a->argc != 4)
01343       return CLI_SHOWUSAGE;
01344 
01345    matches = ast_cli_generatornummatches(a->argv[2], a->argv[3]);
01346 
01347    ast_cli(a->fd, "%d", matches);
01348 
01349    return CLI_SUCCESS;
01350 }
01351 
01352 static char *handle_commandcomplete(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01353 {
01354    char *buf;
01355    switch (cmd) {
01356    case CLI_INIT:
01357       e->command = "_command complete";
01358       e->usage =
01359          "Usage: _command complete \"<line>\" text state\n"
01360          "       This function is used internally to help with command completion and should.\n"
01361          "       never be called by the user directly.\n";
01362       return NULL;
01363    case CLI_GENERATE:
01364       return NULL;
01365    }
01366    if (a->argc != 5)
01367       return CLI_SHOWUSAGE;
01368    buf = __ast_cli_generator(a->argv[2], a->argv[3], atoi(a->argv[4]), 0);
01369    if (buf) {
01370       ast_cli(a->fd, "%s", buf);
01371       ast_free(buf);
01372    } else
01373       ast_cli(a->fd, "NULL\n");
01374    return CLI_SUCCESS;
01375 }
01376 
01377 struct channel_set_debug_args {
01378    int fd;
01379    int is_off;
01380 };
01381 
01382 static int channel_set_debug(void *obj, void *arg, void *data, int flags)
01383 {
01384    struct ast_channel *chan = obj;
01385    struct channel_set_debug_args *args = data;
01386 
01387    ast_channel_lock(chan);
01388 
01389    if (!(ast_channel_fin(chan) & DEBUGCHAN_FLAG) || !(ast_channel_fout(chan) & DEBUGCHAN_FLAG)) {
01390       if (args->is_off) {
01391          ast_channel_fin_set(chan, ast_channel_fin(chan) & ~DEBUGCHAN_FLAG);
01392          ast_channel_fout_set(chan, ast_channel_fout(chan) & ~DEBUGCHAN_FLAG);
01393       } else {
01394          ast_channel_fin_set(chan, ast_channel_fin(chan) | DEBUGCHAN_FLAG);
01395          ast_channel_fout_set(chan, ast_channel_fout(chan) | DEBUGCHAN_FLAG);
01396       }
01397       ast_cli(args->fd, "Debugging %s on channel %s\n", args->is_off ? "disabled" : "enabled",
01398             ast_channel_name(chan));
01399    }
01400 
01401    ast_channel_unlock(chan);
01402 
01403    return 0;
01404 }
01405 
01406 static char *handle_core_set_debug_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01407 {
01408    struct ast_channel *c = NULL;
01409    struct channel_set_debug_args args = {
01410       .fd = a->fd,
01411    };
01412 
01413    switch (cmd) {
01414    case CLI_INIT:
01415       e->command = "core set debug channel";
01416       e->usage =
01417          "Usage: core set debug channel <all|channel> [off]\n"
01418          "       Enables/disables debugging on all or on a specific channel.\n";
01419       return NULL;
01420    case CLI_GENERATE:
01421       /* XXX remember to handle the optional "off" */
01422       if (a->pos != e->args)
01423          return NULL;
01424       return a->n == 0 ? ast_strdup("all") : ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
01425    }
01426 
01427    if (cmd == (CLI_HANDLER + 1000)) {
01428       /* called from handle_nodebugchan_deprecated */
01429       args.is_off = 1;
01430    } else if (a->argc == e->args + 2) {
01431       /* 'core set debug channel {all|chan_id}' */
01432       if (!strcasecmp(a->argv[e->args + 1], "off"))
01433          args.is_off = 1;
01434       else
01435          return CLI_SHOWUSAGE;
01436    } else if (a->argc != e->args + 1) {
01437       return CLI_SHOWUSAGE;
01438    }
01439 
01440    if (!strcasecmp("all", a->argv[e->args])) {
01441       if (args.is_off) {
01442          global_fin &= ~DEBUGCHAN_FLAG;
01443          global_fout &= ~DEBUGCHAN_FLAG;
01444       } else {
01445          global_fin |= DEBUGCHAN_FLAG;
01446          global_fout |= DEBUGCHAN_FLAG;
01447       }
01448       ast_channel_callback(channel_set_debug, NULL, &args, OBJ_NODATA | OBJ_MULTIPLE);
01449    } else {
01450       if ((c = ast_channel_get_by_name(a->argv[e->args]))) {
01451          channel_set_debug(c, NULL, &args, 0);
01452          ast_channel_unref(c);
01453       } else {
01454          ast_cli(a->fd, "No such channel %s\n", a->argv[e->args]);
01455       }
01456    }
01457 
01458    ast_cli(a->fd, "Debugging on new channels is %s\n", args.is_off ? "disabled" : "enabled");
01459 
01460    return CLI_SUCCESS;
01461 }
01462 
01463 static char *handle_nodebugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01464 {
01465    char *res;
01466 
01467    switch (cmd) {
01468    case CLI_INIT:
01469       e->command = "no debug channel";
01470       return NULL;
01471    case CLI_HANDLER:
01472       /* exit out of switch statement */
01473       break;
01474    default:
01475       return NULL;
01476    }
01477 
01478    if (a->argc != e->args + 1)
01479       return CLI_SHOWUSAGE;
01480 
01481    /* add a 'magic' value to the CLI_HANDLER command so that
01482     * handle_core_set_debug_channel() will act as if 'off'
01483     * had been specified as part of the command
01484     */
01485    res = handle_core_set_debug_channel(e, CLI_HANDLER + 1000, a);
01486 
01487    return res;
01488 }
01489 
01490 static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01491 {
01492    struct ast_channel *c=NULL;
01493    struct timeval now;
01494    char cdrtime[256];
01495    char nf[256];
01496    struct ast_str *write_transpath = ast_str_alloca(256);
01497    struct ast_str *read_transpath = ast_str_alloca(256);
01498    struct ast_str *obuf;/*!< Buffer for variable, CDR variable, and trace output. */
01499    struct ast_str *output;/*!< Accumulation buffer for all output. */
01500    long elapsed_seconds=0;
01501    int hour=0, min=0, sec=0;
01502    struct ast_callid *callid;
01503    char call_identifier_str[AST_CALLID_BUFFER_LENGTH] = "";
01504    struct ast_party_id effective_connected_id;
01505 #ifdef CHANNEL_TRACE
01506    int trace_enabled;
01507 #endif
01508 
01509    switch (cmd) {
01510    case CLI_INIT:
01511       e->command = "core show channel";
01512       e->usage =
01513          "Usage: core show channel <channel>\n"
01514          "       Shows lots of information about the specified channel.\n";
01515       return NULL;
01516    case CLI_GENERATE:
01517       return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
01518    }
01519 
01520    if (a->argc != 4) {
01521       return CLI_SHOWUSAGE;
01522    }
01523 
01524    now = ast_tvnow();
01525 
01526    if (!(c = ast_channel_get_by_name(a->argv[3]))) {
01527       ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
01528       return CLI_SUCCESS;
01529    }
01530 
01531    obuf = ast_str_thread_get(&ast_str_thread_global_buf, 16);
01532    if (!obuf) {
01533       return CLI_FAILURE;
01534    }
01535    output = ast_str_create(8192);
01536    if (!output) {
01537       return CLI_FAILURE;
01538    }
01539 
01540    ast_channel_lock(c);
01541 
01542    if (ast_channel_cdr(c)) {
01543       elapsed_seconds = now.tv_sec - ast_channel_cdr(c)->start.tv_sec;
01544       hour = elapsed_seconds / 3600;
01545       min = (elapsed_seconds % 3600) / 60;
01546       sec = elapsed_seconds % 60;
01547       snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
01548    } else {
01549       strcpy(cdrtime, "N/A");
01550    }
01551 
01552    /* Construct the call identifier string based on the status of the channel's call identifier */
01553    if ((callid = ast_channel_callid(c))) {
01554       ast_callid_strnprint(call_identifier_str, sizeof(call_identifier_str), callid);
01555       ast_callid_unref(callid);
01556    }
01557 
01558    effective_connected_id = ast_channel_connected_effective_id(c);
01559 
01560    ast_str_append(&output, 0,
01561       " -- General --\n"
01562       "           Name: %s\n"
01563       "           Type: %s\n"
01564       "       UniqueID: %s\n"
01565       "       LinkedID: %s\n"
01566       "      Caller ID: %s\n"
01567       " Caller ID Name: %s\n"
01568       "Connected Line ID: %s\n"
01569       "Connected Line ID Name: %s\n"
01570       "Eff. Connected Line ID: %s\n"
01571       "Eff. Connected Line ID Name: %s\n"
01572       "    DNID Digits: %s\n"
01573       "       Language: %s\n"
01574       "          State: %s (%d)\n"
01575       "          Rings: %d\n"
01576       "  NativeFormats: %s\n"
01577       "    WriteFormat: %s\n"
01578       "     ReadFormat: %s\n"
01579       " WriteTranscode: %s %s\n"
01580       "  ReadTranscode: %s %s\n"
01581       "1st File Descriptor: %d\n"
01582       "      Frames in: %d%s\n"
01583       "     Frames out: %d%s\n"
01584       " Time to Hangup: %ld\n"
01585       "   Elapsed Time: %s\n"
01586       "  Direct Bridge: %s\n"
01587       "Indirect Bridge: %s\n"
01588       " --   PBX   --\n"
01589       "        Context: %s\n"
01590       "      Extension: %s\n"
01591       "       Priority: %d\n"
01592       "     Call Group: %llu\n"
01593       "   Pickup Group: %llu\n"
01594       "    Application: %s\n"
01595       "           Data: %s\n"
01596       "    Blocking in: %s\n"
01597       " Call Identifer: %s\n",
01598       ast_channel_name(c), ast_channel_tech(c)->type, ast_channel_uniqueid(c), ast_channel_linkedid(c),
01599       S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, "(N/A)"),
01600       S_COR(ast_channel_caller(c)->id.name.valid, ast_channel_caller(c)->id.name.str, "(N/A)"),
01601       S_COR(ast_channel_connected(c)->id.number.valid, ast_channel_connected(c)->id.number.str, "(N/A)"),
01602       S_COR(ast_channel_connected(c)->id.name.valid, ast_channel_connected(c)->id.name.str, "(N/A)"),
01603       S_COR(effective_connected_id.number.valid, effective_connected_id.number.str, "(N/A)"),
01604       S_COR(effective_connected_id.name.valid, effective_connected_id.name.str, "(N/A)"),
01605       S_OR(ast_channel_dialed(c)->number.str, "(N/A)"),
01606       ast_channel_language(c),
01607       ast_state2str(ast_channel_state(c)), ast_channel_state(c), ast_channel_rings(c),
01608       ast_getformatname_multiple(nf, sizeof(nf), ast_channel_nativeformats(c)),
01609       ast_getformatname(ast_channel_writeformat(c)),
01610       ast_getformatname(ast_channel_readformat(c)),
01611       ast_channel_writetrans(c) ? "Yes" : "No",
01612       ast_translate_path_to_str(ast_channel_writetrans(c), &write_transpath),
01613       ast_channel_readtrans(c) ? "Yes" : "No",
01614       ast_translate_path_to_str(ast_channel_readtrans(c), &read_transpath),
01615       ast_channel_fd(c, 0),
01616       ast_channel_fin(c) & ~DEBUGCHAN_FLAG, (ast_channel_fin(c) & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
01617       ast_channel_fout(c) & ~DEBUGCHAN_FLAG, (ast_channel_fout(c) & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
01618       (long)ast_channel_whentohangup(c)->tv_sec,
01619       cdrtime, ast_channel_internal_bridged_channel(c) ? ast_channel_name(ast_channel_internal_bridged_channel(c)) : "<none>", ast_bridged_channel(c) ? ast_channel_name(ast_bridged_channel(c)) : "<none>",
01620       ast_channel_context(c), ast_channel_exten(c), ast_channel_priority(c), ast_channel_callgroup(c), ast_channel_pickupgroup(c), (ast_channel_appl(c) ? ast_channel_appl(c) : "(N/A)" ),
01621       (ast_channel_data(c) ? S_OR(ast_channel_data(c), "(Empty)") : "(None)"),
01622       (ast_test_flag(ast_channel_flags(c), AST_FLAG_BLOCKING) ? ast_channel_blockproc(c) : "(Not Blocking)"),
01623       S_OR(call_identifier_str, "(None)"));
01624 
01625    if (pbx_builtin_serialize_variables(c, &obuf)) {
01626       ast_str_append(&output, 0, "      Variables:\n%s\n", ast_str_buffer(obuf));
01627    }
01628 
01629    if (ast_channel_cdr(c) && ast_cdr_serialize_variables(ast_channel_cdr(c), &obuf, '=', '\n', 1)) {
01630       ast_str_append(&output, 0, "  CDR Variables:\n%s\n", ast_str_buffer(obuf));
01631    }
01632 
01633 #ifdef CHANNEL_TRACE
01634    trace_enabled = ast_channel_trace_is_enabled(c);
01635    ast_str_append(&output, 0, "  Context Trace: %s\n",
01636       trace_enabled ? "Enabled" : "Disabled");
01637    if (trace_enabled && ast_channel_trace_serialize(c, &obuf)) {
01638       ast_str_append(&output, 0, "          Trace:\n%s\n", ast_str_buffer(obuf));
01639    }
01640 #endif
01641 
01642    ast_channel_unlock(c);
01643    c = ast_channel_unref(c);
01644 
01645    ast_cli(a->fd, "%s", ast_str_buffer(output));
01646    ast_free(output);
01647    return CLI_SUCCESS;
01648 }
01649 
01650 /*
01651  * helper function to generate CLI matches from a fixed set of values.
01652  * A NULL word is acceptable.
01653  */
01654 char *ast_cli_complete(const char *word, const char * const choices[], int state)
01655 {
01656    int i, which = 0, len;
01657    len = ast_strlen_zero(word) ? 0 : strlen(word);
01658 
01659    for (i = 0; choices[i]; i++) {
01660       if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
01661          return ast_strdup(choices[i]);
01662    }
01663    return NULL;
01664 }
01665 
01666 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
01667 {
01668    struct ast_channel *c = NULL;
01669    int which = 0;
01670    char notfound = '\0';
01671    char *ret = &notfound; /* so NULL can break the loop */
01672    struct ast_channel_iterator *iter;
01673 
01674    if (pos != rpos) {
01675       return NULL;
01676    }
01677 
01678    if (ast_strlen_zero(word)) {
01679       iter = ast_channel_iterator_all_new();
01680    } else {
01681       iter = ast_channel_iterator_by_name_new(word, strlen(word));
01682    }
01683 
01684    if (!iter) {
01685       return NULL;
01686    }
01687 
01688    while (ret == &notfound && (c = ast_channel_iterator_next(iter))) {
01689       if (++which > state) {
01690          ast_channel_lock(c);
01691          ret = ast_strdup(ast_channel_name(c));
01692          ast_channel_unlock(c);
01693       }
01694       ast_channel_unref(c);
01695    }
01696 
01697    ast_channel_iterator_destroy(iter);
01698 
01699    return ret == &notfound ? NULL : ret;
01700 }
01701 
01702 static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01703 {
01704 #define FORMAT_STRING  "%-25s  %-20s  %-20s\n"
01705 
01706    struct ast_group_info *gi = NULL;
01707    int numchans = 0;
01708    regex_t regexbuf;
01709    int havepattern = 0;
01710 
01711    switch (cmd) {
01712    case CLI_INIT:
01713       e->command = "group show channels";
01714       e->usage =
01715          "Usage: group show channels [pattern]\n"
01716          "       Lists all currently active channels with channel group(s) specified.\n"
01717          "       Optional regular expression pattern is matched to group names for each\n"
01718          "       channel.\n";
01719       return NULL;
01720    case CLI_GENERATE:
01721       return NULL;
01722    }
01723 
01724    if (a->argc < 3 || a->argc > 4)
01725       return CLI_SHOWUSAGE;
01726 
01727    if (a->argc == 4) {
01728       if (regcomp(&regexbuf, a->argv[3], REG_EXTENDED | REG_NOSUB))
01729          return CLI_SHOWUSAGE;
01730       havepattern = 1;
01731    }
01732 
01733    ast_cli(a->fd, FORMAT_STRING, "Channel", "Group", "Category");
01734 
01735    ast_app_group_list_rdlock();
01736 
01737    gi = ast_app_group_list_head();
01738    while (gi) {
01739       if (!havepattern || !regexec(&regexbuf, gi->group, 0, NULL, 0)) {
01740          ast_cli(a->fd, FORMAT_STRING, ast_channel_name(gi->chan), gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category));
01741          numchans++;
01742       }
01743       gi = AST_LIST_NEXT(gi, group_list);
01744    }
01745 
01746    ast_app_group_list_unlock();
01747 
01748    if (havepattern)
01749       regfree(&regexbuf);
01750 
01751    ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
01752    return CLI_SUCCESS;
01753 #undef FORMAT_STRING
01754 }
01755 
01756 static char *handle_cli_wait_fullybooted(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01757 {
01758    switch (cmd) {
01759    case CLI_INIT:
01760       e->command = "core waitfullybooted";
01761       e->usage =
01762          "Usage: core waitfullybooted\n"
01763          "  Wait until Asterisk has fully booted.\n";
01764       return NULL;
01765    case CLI_GENERATE:
01766       return NULL;
01767    }
01768 
01769    while (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
01770       usleep(100);
01771    }
01772 
01773    ast_cli(a->fd, "Asterisk has fully booted.\n");
01774 
01775    return CLI_SUCCESS;
01776 }
01777 
01778 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01779 
01780 static struct ast_cli_entry cli_cli[] = {
01781    /* Deprecated, but preferred command is now consolidated (and already has a deprecated command for it). */
01782    AST_CLI_DEFINE(handle_commandcomplete, "Command complete"),
01783    AST_CLI_DEFINE(handle_commandnummatches, "Returns number of command matches"),
01784    AST_CLI_DEFINE(handle_commandmatchesarray, "Returns command matches array"),
01785 
01786    AST_CLI_DEFINE(handle_nodebugchan_deprecated, "Disable debugging on channel(s)"),
01787 
01788    AST_CLI_DEFINE(handle_chanlist, "Display information on channels"),
01789 
01790    AST_CLI_DEFINE(handle_showcalls, "Display information on calls"),
01791 
01792    AST_CLI_DEFINE(handle_showchan, "Display information on a specific channel"),
01793 
01794    AST_CLI_DEFINE(handle_core_set_debug_channel, "Enable/disable debugging on a channel"),
01795 
01796    AST_CLI_DEFINE(handle_debug, "Set level of debug chattiness"),
01797    AST_CLI_DEFINE(handle_verbose, "Set level of verbose chattiness"),
01798 
01799    AST_CLI_DEFINE(group_show_channels, "Display active channels with group(s)"),
01800 
01801    AST_CLI_DEFINE(handle_help, "Display help list, or specific help on a command"),
01802 
01803    AST_CLI_DEFINE(handle_logger_mute, "Toggle logging output to a console"),
01804 
01805    AST_CLI_DEFINE(handle_modlist, "List modules and info"),
01806 
01807    AST_CLI_DEFINE(handle_load, "Load a module by name"),
01808 
01809    AST_CLI_DEFINE(handle_reload, "Reload configuration for a module"),
01810 
01811    AST_CLI_DEFINE(handle_core_reload, "Global reload"),
01812 
01813    AST_CLI_DEFINE(handle_unload, "Unload a module by name"),
01814 
01815    AST_CLI_DEFINE(handle_showuptime, "Show uptime information"),
01816 
01817    AST_CLI_DEFINE(handle_softhangup, "Request a hangup on a given channel"),
01818 
01819    AST_CLI_DEFINE(handle_cli_reload_permissions, "Reload CLI permissions config"),
01820 
01821    AST_CLI_DEFINE(handle_cli_show_permissions, "Show CLI permissions"),
01822 
01823    AST_CLI_DEFINE(handle_cli_check_permissions, "Try a permissions config for a user"),
01824 
01825    AST_CLI_DEFINE(handle_cli_wait_fullybooted, "Wait for Asterisk to be fully booted"),
01826 };
01827 
01828 /*!
01829  * Some regexp characters in cli arguments are reserved and used as separators.
01830  */
01831 static const char cli_rsvd[] = "[]{}|*%";
01832 
01833 /*!
01834  * initialize the _full_cmd string and related parameters,
01835  * return 0 on success, -1 on error.
01836  */
01837 static int set_full_cmd(struct ast_cli_entry *e)
01838 {
01839    int i;
01840    char buf[80];
01841 
01842    ast_join(buf, sizeof(buf), e->cmda);
01843    e->_full_cmd = ast_strdup(buf);
01844    if (!e->_full_cmd) {
01845       ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
01846       return -1;
01847    }
01848    e->cmdlen = strcspn(e->_full_cmd, cli_rsvd);
01849    for (i = 0; e->cmda[i]; i++)
01850       ;
01851    e->args = i;
01852    return 0;
01853 }
01854 
01855 /*! \brief cleanup (free) cli_perms linkedlist. */
01856 static void destroy_user_perms(void)
01857 {
01858    struct cli_perm *perm;
01859    struct usergroup_cli_perm *user_perm;
01860 
01861    AST_RWLIST_WRLOCK(&cli_perms);
01862    while ((user_perm = AST_LIST_REMOVE_HEAD(&cli_perms, list))) {
01863       while ((perm = AST_LIST_REMOVE_HEAD(user_perm->perms, list))) {
01864          ast_free(perm->command);
01865          ast_free(perm);
01866       }
01867       ast_free(user_perm);
01868    }
01869    AST_RWLIST_UNLOCK(&cli_perms);
01870 }
01871 
01872 int ast_cli_perms_init(int reload)
01873 {
01874    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
01875    struct ast_config *cfg;
01876    char *cat = NULL;
01877    struct ast_variable *v;
01878    struct usergroup_cli_perm *user_group, *cp_entry;
01879    struct cli_perm *perm = NULL;
01880    struct passwd *pw;
01881    struct group *gr;
01882 
01883    if (ast_mutex_trylock(&permsconfiglock)) {
01884       ast_log(LOG_NOTICE, "You must wait until last 'cli reload permissions' command finish\n");
01885       return 1;
01886    }
01887 
01888    cfg = ast_config_load2(perms_config, "" /* core, can't reload */, config_flags);
01889    if (!cfg) {
01890       ast_mutex_unlock(&permsconfiglock);
01891       return 1;
01892    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
01893       ast_mutex_unlock(&permsconfiglock);
01894       return 0;
01895    }
01896 
01897    /* free current structures. */
01898    destroy_user_perms();
01899 
01900    while ((cat = ast_category_browse(cfg, cat))) {
01901       if (!strcasecmp(cat, "general")) {
01902          /* General options */
01903          for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
01904             if (!strcasecmp(v->name, "default_perm")) {
01905                cli_default_perm = (!strcasecmp(v->value, "permit")) ? 1: 0;
01906             }
01907          }
01908          continue;
01909       }
01910 
01911       /* users or groups */
01912       gr = NULL, pw = NULL;
01913       if (cat[0] == '@') {
01914          /* This is a group */
01915          gr = getgrnam(&cat[1]);
01916          if (!gr) {
01917             ast_log (LOG_WARNING, "Unknown group '%s'\n", &cat[1]);
01918             continue;
01919          }
01920       } else {
01921          /* This is a user */
01922          pw = getpwnam(cat);
01923          if (!pw) {
01924             ast_log (LOG_WARNING, "Unknown user '%s'\n", cat);
01925             continue;
01926          }
01927       }
01928       user_group = NULL;
01929       /* Check for duplicates */
01930       AST_RWLIST_WRLOCK(&cli_perms);
01931       AST_LIST_TRAVERSE(&cli_perms, cp_entry, list) {
01932          if ((pw && cp_entry->uid == pw->pw_uid) || (gr && cp_entry->gid == gr->gr_gid)) {
01933             /* if it is duplicated, just added this new settings, to
01934             the current list. */
01935             user_group = cp_entry;
01936             break;
01937          }
01938       }
01939       AST_RWLIST_UNLOCK(&cli_perms);
01940 
01941       if (!user_group) {
01942          /* alloc space for the new user config. */
01943          user_group = ast_calloc(1, sizeof(*user_group));
01944          if (!user_group) {
01945             continue;
01946          }
01947          user_group->uid = (pw ? pw->pw_uid : -1);
01948          user_group->gid = (gr ? gr->gr_gid : -1);
01949          user_group->perms = ast_calloc(1, sizeof(*user_group->perms));
01950          if (!user_group->perms) {
01951             ast_free(user_group);
01952             continue;
01953          }
01954       }
01955       for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
01956          if (ast_strlen_zero(v->value)) {
01957             /* we need to check this condition cause it could break security. */
01958             ast_log(LOG_WARNING, "Empty permit/deny option in user '%s'\n", cat);
01959             continue;
01960          }
01961          if (!strcasecmp(v->name, "permit")) {
01962             perm = ast_calloc(1, sizeof(*perm));
01963             if (perm) {
01964                perm->permit = 1;
01965                perm->command = ast_strdup(v->value);
01966             }
01967          } else if (!strcasecmp(v->name, "deny")) {
01968             perm = ast_calloc(1, sizeof(*perm));
01969             if (perm) {
01970                perm->permit = 0;
01971                perm->command = ast_strdup(v->value);
01972             }
01973          } else {
01974             /* up to now, only 'permit' and 'deny' are possible values. */
01975             ast_log(LOG_WARNING, "Unknown '%s' option\n", v->name);
01976             continue;
01977          }
01978          if (perm) {
01979             /* Added the permission to the user's list. */
01980             AST_LIST_INSERT_TAIL(user_group->perms, perm, list);
01981             perm = NULL;
01982          }
01983       }
01984       AST_RWLIST_WRLOCK(&cli_perms);
01985       AST_RWLIST_INSERT_TAIL(&cli_perms, user_group, list);
01986       AST_RWLIST_UNLOCK(&cli_perms);
01987    }
01988 
01989    ast_config_destroy(cfg);
01990    ast_mutex_unlock(&permsconfiglock);
01991    return 0;
01992 }
01993 
01994 static void cli_shutdown(void)
01995 {
01996    ast_cli_unregister_multiple(cli_cli, ARRAY_LEN(cli_cli));
01997 }
01998 
01999 /*! \brief initialize the _full_cmd string in * each of the builtins. */
02000 void ast_builtins_init(void)
02001 {
02002    ast_cli_register_multiple(cli_cli, ARRAY_LEN(cli_cli));
02003    ast_register_atexit(cli_shutdown);
02004 }
02005 
02006 /*!
02007  * match a word in the CLI entry.
02008  * returns -1 on mismatch, 0 on match of an optional word,
02009  * 1 on match of a full word.
02010  *
02011  * The pattern can be
02012  *   any_word           match for equal
02013  *   [foo|bar|baz]      optionally, one of these words
02014  *   {foo|bar|baz}      exactly, one of these words
02015  *   %                  any word
02016  */
02017 static int word_match(const char *cmd, const char *cli_word)
02018 {
02019    int l;
02020    char *pos;
02021 
02022    if (ast_strlen_zero(cmd) || ast_strlen_zero(cli_word))
02023       return -1;
02024    if (!strchr(cli_rsvd, cli_word[0])) /* normal match */
02025       return (strcasecmp(cmd, cli_word) == 0) ? 1 : -1;
02026    l = strlen(cmd);
02027    /* wildcard match - will extend in the future */
02028    if (l > 0 && cli_word[0] == '%') {
02029       return 1;   /* wildcard */
02030    }
02031 
02032    /* Start a search for the command entered against the cli word in question */
02033    pos = strcasestr(cli_word, cmd);
02034    while (pos) {
02035 
02036       /*
02037        *Check if the word matched with is surrounded by reserved characters on both sides
02038        * and isn't at the beginning of the cli_word since that would make it check in a location we shouldn't know about.
02039        * If it is surrounded by reserved chars and isn't at the beginning, it's a match.
02040        */
02041       if (pos != cli_word && strchr(cli_rsvd, pos[-1]) && strchr(cli_rsvd, pos[l])) {
02042          return 1;   /* valid match */
02043       }
02044 
02045       /* Ok, that one didn't match, strcasestr to the next appearance of the command and start over.*/
02046       pos = strcasestr(pos + 1, cmd);
02047    }
02048    /* If no matches were found over the course of the while loop, we hit the end of the string. It's a mismatch. */
02049    return -1;
02050 }
02051 
02052 /*! \brief if word is a valid prefix for token, returns the pos-th
02053  * match as a malloced string, or NULL otherwise.
02054  * Always tell in *actual how many matches we got.
02055  */
02056 static char *is_prefix(const char *word, const char *token,
02057    int pos, int *actual)
02058 {
02059    int lw;
02060    char *s, *t1;
02061 
02062    *actual = 0;
02063    if (ast_strlen_zero(token))
02064       return NULL;
02065    if (ast_strlen_zero(word))
02066       word = "";  /* dummy */
02067    lw = strlen(word);
02068    if (strcspn(word, cli_rsvd) != lw)
02069       return NULL;   /* no match if word has reserved chars */
02070    if (strchr(cli_rsvd, token[0]) == NULL) { /* regular match */
02071       if (strncasecmp(token, word, lw))   /* no match */
02072          return NULL;
02073       *actual = 1;
02074       return (pos != 0) ? NULL : ast_strdup(token);
02075    }
02076    /* now handle regexp match */
02077 
02078    /* Wildcard always matches, so we never do is_prefix on them */
02079 
02080    t1 = ast_strdupa(token + 1);  /* copy, skipping first char */
02081    while (pos >= 0 && (s = strsep(&t1, cli_rsvd)) && *s) {
02082       if (*s == '%') /* wildcard */
02083          continue;
02084       if (strncasecmp(s, word, lw)) /* no match */
02085          continue;
02086       (*actual)++;
02087       if (pos-- == 0)
02088          return ast_strdup(s);
02089    }
02090    return NULL;
02091 }
02092 
02093 /*!
02094  * \internal
02095  * \brief locate a cli command in the 'helpers' list (which must be locked).
02096  *     The search compares word by word taking care of regexps in e->cmda
02097  *     This function will return NULL when nothing is matched, or the ast_cli_entry that matched.
02098  * \param cmds
02099  * \param match_type has 3 possible values:
02100  *      0       returns if the search key is equal or longer than the entry.
02101  *                note that trailing optional arguments are skipped.
02102  *      -1      true if the mismatch is on the last word XXX not true!
02103  *      1       true only on complete, exact match.
02104  *
02105  */
02106 static struct ast_cli_entry *find_cli(const char * const cmds[], int match_type)
02107 {
02108    int matchlen = -1;   /* length of longest match so far */
02109    struct ast_cli_entry *cand = NULL, *e=NULL;
02110 
02111    while ( (e = cli_next(e)) ) {
02112       /* word-by word regexp comparison */
02113       const char * const *src = cmds;
02114       const char * const *dst = e->cmda;
02115       int n = 0;
02116       for (;; dst++, src += n) {
02117          n = word_match(*src, *dst);
02118          if (n < 0)
02119             break;
02120       }
02121       if (ast_strlen_zero(*dst) || ((*dst)[0] == '[' && ast_strlen_zero(dst[1]))) {
02122          /* no more words in 'e' */
02123          if (ast_strlen_zero(*src)) /* exact match, cannot do better */
02124             break;
02125          /* Here, cmds has more words than the entry 'e' */
02126          if (match_type != 0) /* but we look for almost exact match... */
02127             continue;   /* so we skip this one. */
02128          /* otherwise we like it (case 0) */
02129       } else { /* still words in 'e' */
02130          if (ast_strlen_zero(*src))
02131             continue; /* cmds is shorter than 'e', not good */
02132          /* Here we have leftover words in cmds and 'e',
02133           * but there is a mismatch. We only accept this one if match_type == -1
02134           * and this is the last word for both.
02135           */
02136          if (match_type != -1 || !ast_strlen_zero(src[1]) ||
02137              !ast_strlen_zero(dst[1])) /* not the one we look for */
02138             continue;
02139          /* good, we are in case match_type == -1 and mismatch on last word */
02140       }
02141       if (src - cmds > matchlen) {  /* remember the candidate */
02142          matchlen = src - cmds;
02143          cand = e;
02144       }
02145    }
02146 
02147    return e ? e : cand;
02148 }
02149 
02150 static char *find_best(const char *argv[])
02151 {
02152    static char cmdline[80];
02153    int x;
02154    /* See how close we get, then print the candidate */
02155    const char *myargv[AST_MAX_CMD_LEN] = { NULL, };
02156 
02157    AST_RWLIST_RDLOCK(&helpers);
02158    for (x = 0; argv[x]; x++) {
02159       myargv[x] = argv[x];
02160       if (!find_cli(myargv, -1))
02161          break;
02162    }
02163    AST_RWLIST_UNLOCK(&helpers);
02164    ast_join(cmdline, sizeof(cmdline), myargv);
02165    return cmdline;
02166 }
02167 
02168 static int cli_is_registered(struct ast_cli_entry *e)
02169 {
02170    struct ast_cli_entry *cur = NULL;
02171 
02172    while ((cur = cli_next(cur))) {
02173       if (cur == e) {
02174          return 1;
02175       }
02176    }
02177    return 0;
02178 }
02179 
02180 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
02181 {
02182    if (e->inuse) {
02183       ast_log(LOG_WARNING, "Can't remove command that is in use\n");
02184    } else {
02185       AST_RWLIST_WRLOCK(&helpers);
02186       AST_RWLIST_REMOVE(&helpers, e, list);
02187       AST_RWLIST_UNLOCK(&helpers);
02188       ast_free(e->_full_cmd);
02189       e->_full_cmd = NULL;
02190       if (e->handler) {
02191          /* this is a new-style entry. Reset fields and free memory. */
02192          char *cmda = (char *) e->cmda;
02193          memset(cmda, '\0', sizeof(e->cmda));
02194          ast_free(e->command);
02195          e->command = NULL;
02196          e->usage = NULL;
02197       }
02198    }
02199    return 0;
02200 }
02201 
02202 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
02203 {
02204    struct ast_cli_entry *cur;
02205    int i, lf, ret = -1;
02206 
02207    struct ast_cli_args a;  /* fake argument */
02208    char **dst = (char **)e->cmda;   /* need to cast as the entry is readonly */
02209    char *s;
02210 
02211    AST_RWLIST_WRLOCK(&helpers);
02212 
02213    if (cli_is_registered(e)) {
02214       ast_log(LOG_WARNING, "Command '%s' already registered (the same ast_cli_entry)\n",
02215          S_OR(e->_full_cmd, e->command));
02216       ret = 0;  /* report success */
02217       goto done;
02218    }
02219 
02220    memset(&a, '\0', sizeof(a));
02221    e->handler(e, CLI_INIT, &a);
02222    /* XXX check that usage and command are filled up */
02223    s = ast_skip_blanks(e->command);
02224    s = e->command = ast_strdup(s);
02225    for (i=0; !ast_strlen_zero(s) && i < AST_MAX_CMD_LEN-1; i++) {
02226       *dst++ = s; /* store string */
02227       s = ast_skip_nonblanks(s);
02228       if (*s == '\0')   /* we are done */
02229          break;
02230       *s++ = '\0';
02231       s = ast_skip_blanks(s);
02232    }
02233    *dst++ = NULL;
02234 
02235    if (find_cli(e->cmda, 1)) {
02236       ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n",
02237          S_OR(e->_full_cmd, e->command));
02238       goto done;
02239    }
02240    if (set_full_cmd(e)) {
02241       ast_log(LOG_WARNING, "Error registering CLI Command '%s'\n",
02242          S_OR(e->_full_cmd, e->command));
02243       goto done;
02244    }
02245 
02246    lf = e->cmdlen;
02247    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
02248       int len = cur->cmdlen;
02249       if (lf < len)
02250          len = lf;
02251       if (strncasecmp(e->_full_cmd, cur->_full_cmd, len) < 0) {
02252          AST_RWLIST_INSERT_BEFORE_CURRENT(e, list);
02253          break;
02254       }
02255    }
02256    AST_RWLIST_TRAVERSE_SAFE_END;
02257 
02258    if (!cur)
02259       AST_RWLIST_INSERT_TAIL(&helpers, e, list);
02260    ret = 0; /* success */
02261 
02262 done:
02263    AST_RWLIST_UNLOCK(&helpers);
02264    if (ret) {
02265       ast_free(e->command);
02266       e->command = NULL;
02267    }
02268 
02269    return ret;
02270 }
02271 
02272 /* wrapper function, so we can unregister deprecated commands recursively */
02273 int ast_cli_unregister(struct ast_cli_entry *e)
02274 {
02275    return __ast_cli_unregister(e, NULL);
02276 }
02277 
02278 /* wrapper function, so we can register deprecated commands recursively */
02279 int ast_cli_register(struct ast_cli_entry *e)
02280 {
02281    return __ast_cli_register(e, NULL);
02282 }
02283 
02284 /*
02285  * register/unregister an array of entries.
02286  */
02287 int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
02288 {
02289    int i, res = 0;
02290 
02291    for (i = 0; i < len; i++)
02292       res |= ast_cli_register(e + i);
02293 
02294    return res;
02295 }
02296 
02297 int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
02298 {
02299    int i, res = 0;
02300 
02301    for (i = 0; i < len; i++)
02302       res |= ast_cli_unregister(e + i);
02303 
02304    return res;
02305 }
02306 
02307 
02308 /*! \brief helper for final part of handle_help
02309  *  if locked = 1, assume the list is already locked
02310  */
02311 static char *help1(int fd, const char * const match[], int locked)
02312 {
02313    char matchstr[80] = "";
02314    struct ast_cli_entry *e = NULL;
02315    int len = 0;
02316    int found = 0;
02317 
02318    if (match) {
02319       ast_join(matchstr, sizeof(matchstr), match);
02320       len = strlen(matchstr);
02321    }
02322    if (!locked)
02323       AST_RWLIST_RDLOCK(&helpers);
02324    while ( (e = cli_next(e)) ) {
02325       /* Hide commands that start with '_' */
02326       if (e->_full_cmd[0] == '_')
02327          continue;
02328       if (match && strncasecmp(matchstr, e->_full_cmd, len))
02329          continue;
02330       ast_cli(fd, "%30.30s %s\n", e->_full_cmd, S_OR(e->summary, "<no description available>"));
02331       found++;
02332    }
02333    if (!locked)
02334       AST_RWLIST_UNLOCK(&helpers);
02335    if (!found && matchstr[0])
02336       ast_cli(fd, "No such command '%s'.\n", matchstr);
02337    return CLI_SUCCESS;
02338 }
02339 
02340 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02341 {
02342    char fullcmd[80];
02343    struct ast_cli_entry *my_e;
02344    char *res = CLI_SUCCESS;
02345 
02346    if (cmd == CLI_INIT) {
02347       e->command = "core show help";
02348       e->usage =
02349          "Usage: core show help [topic]\n"
02350          "       When called with a topic as an argument, displays usage\n"
02351          "       information on the given command. If called without a\n"
02352          "       topic, it provides a list of commands.\n";
02353       return NULL;
02354 
02355    } else if (cmd == CLI_GENERATE) {
02356       /* skip first 14 or 15 chars, "core show help " */
02357       int l = strlen(a->line);
02358 
02359       if (l > 15) {
02360          l = 15;
02361       }
02362       /* XXX watch out, should stop to the non-generator parts */
02363       return __ast_cli_generator(a->line + l, a->word, a->n, 0);
02364    }
02365    if (a->argc == e->args) {
02366       return help1(a->fd, NULL, 0);
02367    }
02368 
02369    AST_RWLIST_RDLOCK(&helpers);
02370    my_e = find_cli(a->argv + 3, 1); /* try exact match first */
02371    if (!my_e) {
02372       res = help1(a->fd, a->argv + 3, 1 /* locked */);
02373       AST_RWLIST_UNLOCK(&helpers);
02374       return res;
02375    }
02376    if (my_e->usage)
02377       ast_cli(a->fd, "%s", my_e->usage);
02378    else {
02379       ast_join(fullcmd, sizeof(fullcmd), a->argv + 3);
02380       ast_cli(a->fd, "No help text available for '%s'.\n", fullcmd);
02381    }
02382    AST_RWLIST_UNLOCK(&helpers);
02383    return res;
02384 }
02385 
02386 static char *parse_args(const char *s, int *argc, const char *argv[], int max, int *trailingwhitespace)
02387 {
02388    char *duplicate, *cur;
02389    int x = 0;
02390    int quoted = 0;
02391    int escaped = 0;
02392    int whitespace = 1;
02393    int dummy = 0;
02394 
02395    if (trailingwhitespace == NULL)
02396       trailingwhitespace = &dummy;
02397    *trailingwhitespace = 0;
02398    if (s == NULL) /* invalid, though! */
02399       return NULL;
02400    /* make a copy to store the parsed string */
02401    if (!(duplicate = ast_strdup(s)))
02402       return NULL;
02403 
02404    cur = duplicate;
02405 
02406    /* Remove leading spaces from the command */
02407    while (isspace(*s)) {
02408       cur++;
02409       s++;
02410    }
02411 
02412    /* scan the original string copying into cur when needed */
02413    for (; *s ; s++) {
02414       if (x >= max - 1) {
02415          ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
02416          break;
02417       }
02418       if (*s == '"' && !escaped) {
02419          quoted = !quoted;
02420          if (quoted && whitespace) {
02421             /* start a quoted string from previous whitespace: new argument */
02422             argv[x++] = cur;
02423             whitespace = 0;
02424          }
02425       } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
02426          /* If we are not already in whitespace, and not in a quoted string or
02427             processing an escape sequence, and just entered whitespace, then
02428             finalize the previous argument and remember that we are in whitespace
02429          */
02430          if (!whitespace) {
02431             *cur++ = '\0';
02432             whitespace = 1;
02433          }
02434       } else if (*s == '\\' && !escaped) {
02435          escaped = 1;
02436       } else {
02437          if (whitespace) {
02438             /* we leave whitespace, and are not quoted. So it's a new argument */
02439             argv[x++] = cur;
02440             whitespace = 0;
02441          }
02442          *cur++ = *s;
02443          escaped = 0;
02444       }
02445    }
02446    /* Null terminate */
02447    *cur++ = '\0';
02448    /* XXX put a NULL in the last argument, because some functions that take
02449     * the array may want a null-terminated array.
02450     * argc still reflects the number of non-NULL entries.
02451     */
02452    argv[x] = NULL;
02453    *argc = x;
02454    *trailingwhitespace = whitespace;
02455    return duplicate;
02456 }
02457 
02458 /*! \brief Return the number of unique matches for the generator */
02459 int ast_cli_generatornummatches(const char *text, const char *word)
02460 {
02461    int matches = 0, i = 0;
02462    char *buf = NULL, *oldbuf = NULL;
02463 
02464    while ((buf = ast_cli_generator(text, word, i++))) {
02465       if (!oldbuf || strcmp(buf,oldbuf))
02466          matches++;
02467       if (oldbuf)
02468          ast_free(oldbuf);
02469       oldbuf = buf;
02470    }
02471    if (oldbuf)
02472       ast_free(oldbuf);
02473    return matches;
02474 }
02475 
02476 static void destroy_match_list(char **match_list, int matches)
02477 {
02478    if (match_list) {
02479       int idx;
02480 
02481       for (idx = 1; idx < matches; ++idx) {
02482          ast_free(match_list[idx]);
02483       }
02484       ast_free(match_list);
02485    }
02486 }
02487 
02488 char **ast_cli_completion_matches(const char *text, const char *word)
02489 {
02490    char **match_list = NULL, *retstr, *prevstr;
02491    char **new_list;
02492    size_t match_list_len, max_equal, which, i;
02493    int matches = 0;
02494 
02495    /* leave entry 0 free for the longest common substring */
02496    match_list_len = 1;
02497    while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
02498       if (matches + 1 >= match_list_len) {
02499          match_list_len <<= 1;
02500          new_list = ast_realloc(match_list, match_list_len * sizeof(*match_list));
02501          if (!new_list) {
02502             destroy_match_list(match_list, matches);
02503             return NULL;
02504          }
02505          match_list = new_list;
02506       }
02507       match_list[++matches] = retstr;
02508    }
02509 
02510    if (!match_list) {
02511       return match_list; /* NULL */
02512    }
02513 
02514    /* Find the longest substring that is common to all results
02515     * (it is a candidate for completion), and store a copy in entry 0.
02516     */
02517    prevstr = match_list[1];
02518    max_equal = strlen(prevstr);
02519    for (which = 2; which <= matches; which++) {
02520       for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
02521          continue;
02522       max_equal = i;
02523    }
02524 
02525    retstr = ast_malloc(max_equal + 1);
02526    if (!retstr) {
02527       destroy_match_list(match_list, matches);
02528       return NULL;
02529    }
02530    ast_copy_string(retstr, match_list[1], max_equal + 1);
02531    match_list[0] = retstr;
02532 
02533    /* ensure that the array is NULL terminated */
02534    if (matches + 1 >= match_list_len) {
02535       new_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list));
02536       if (!new_list) {
02537          ast_free(retstr);
02538          destroy_match_list(match_list, matches);
02539          return NULL;
02540       }
02541       match_list = new_list;
02542    }
02543    match_list[matches + 1] = NULL;
02544 
02545    return match_list;
02546 }
02547 
02548 /*! \brief returns true if there are more words to match */
02549 static int more_words (const char * const *dst)
02550 {
02551    int i;
02552    for (i = 0; dst[i]; i++) {
02553       if (dst[i][0] != '[')
02554          return -1;
02555    }
02556    return 0;
02557 }
02558 
02559 /*
02560  * generate the entry at position 'state'
02561  */
02562 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
02563 {
02564    const char *argv[AST_MAX_ARGS];
02565    struct ast_cli_entry *e = NULL;
02566    int x = 0, argindex, matchlen;
02567    int matchnum=0;
02568    char *ret = NULL;
02569    char matchstr[80] = "";
02570    int tws = 0;
02571    /* Split the argument into an array of words */
02572    char *duplicate = parse_args(text, &x, argv, ARRAY_LEN(argv), &tws);
02573 
02574    if (!duplicate)   /* malloc error */
02575       return NULL;
02576 
02577    /* Compute the index of the last argument (could be an empty string) */
02578    argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
02579 
02580    /* rebuild the command, ignore terminating white space and flatten space */
02581    ast_join(matchstr, sizeof(matchstr)-1, argv);
02582    matchlen = strlen(matchstr);
02583    if (tws) {
02584       strcat(matchstr, " "); /* XXX */
02585       if (matchlen)
02586          matchlen++;
02587    }
02588    if (lock)
02589       AST_RWLIST_RDLOCK(&helpers);
02590    while ( (e = cli_next(e)) ) {
02591       /* XXX repeated code */
02592       int src = 0, dst = 0, n = 0;
02593 
02594       if (e->command[0] == '_')
02595          continue;
02596 
02597       /*
02598        * Try to match words, up to and excluding the last word, which
02599        * is either a blank or something that we want to extend.
02600        */
02601       for (;src < argindex; dst++, src += n) {
02602          n = word_match(argv[src], e->cmda[dst]);
02603          if (n < 0)
02604             break;
02605       }
02606 
02607       if (src != argindex && more_words(e->cmda + dst))  /* not a match */
02608          continue;
02609       ret = is_prefix(argv[src], e->cmda[dst], state - matchnum, &n);
02610       matchnum += n; /* this many matches here */
02611       if (ret) {
02612          /*
02613           * argv[src] is a valid prefix of the next word in this
02614           * command. If this is also the correct entry, return it.
02615           */
02616          if (matchnum > state)
02617             break;
02618          ast_free(ret);
02619          ret = NULL;
02620       } else if (ast_strlen_zero(e->cmda[dst])) {
02621          /*
02622           * This entry is a prefix of the command string entered
02623           * (only one entry in the list should have this property).
02624           * Run the generator if one is available. In any case we are done.
02625           */
02626          if (e->handler) { /* new style command */
02627             struct ast_cli_args a = {
02628                .line = matchstr, .word = word,
02629                .pos = argindex,
02630                .n = state - matchnum,
02631                .argv = argv,
02632                .argc = x};
02633             ret = e->handler(e, CLI_GENERATE, &a);
02634          }
02635          if (ret)
02636             break;
02637       }
02638    }
02639    if (lock)
02640       AST_RWLIST_UNLOCK(&helpers);
02641    ast_free(duplicate);
02642    return ret;
02643 }
02644 
02645 char *ast_cli_generator(const char *text, const char *word, int state)
02646 {
02647    return __ast_cli_generator(text, word, state, 1);
02648 }
02649 
02650 int ast_cli_command_full(int uid, int gid, int fd, const char *s)
02651 {
02652    const char *args[AST_MAX_ARGS + 1];
02653    struct ast_cli_entry *e;
02654    int x;
02655    char *duplicate = parse_args(s, &x, args + 1, AST_MAX_ARGS, NULL);
02656    char tmp[AST_MAX_ARGS + 1];
02657    char *retval = NULL;
02658    struct ast_cli_args a = {
02659       .fd = fd, .argc = x, .argv = args+1 };
02660 
02661    if (duplicate == NULL)
02662       return -1;
02663 
02664    if (x < 1)  /* We need at least one entry, otherwise ignore */
02665       goto done;
02666 
02667    AST_RWLIST_RDLOCK(&helpers);
02668    e = find_cli(args + 1, 0);
02669    if (e)
02670       ast_atomic_fetchadd_int(&e->inuse, 1);
02671    AST_RWLIST_UNLOCK(&helpers);
02672    if (e == NULL) {
02673       ast_cli(fd, "No such command '%s' (type 'core show help %s' for other possible commands)\n", s, find_best(args + 1));
02674       goto done;
02675    }
02676 
02677    ast_join(tmp, sizeof(tmp), args + 1);
02678    /* Check if the user has rights to run this command. */
02679    if (!cli_has_permissions(uid, gid, tmp)) {
02680       ast_cli(fd, "You don't have permissions to run '%s' command\n", tmp);
02681       ast_free(duplicate);
02682       return 0;
02683    }
02684 
02685    /*
02686     * Within the handler, argv[-1] contains a pointer to the ast_cli_entry.
02687     * Remember that the array returned by parse_args is NULL-terminated.
02688     */
02689    args[0] = (char *)e;
02690 
02691    retval = e->handler(e, CLI_HANDLER, &a);
02692 
02693    if (retval == CLI_SHOWUSAGE) {
02694       ast_cli(fd, "%s", S_OR(e->usage, "Invalid usage, but no usage information available.\n"));
02695    } else {
02696       if (retval == CLI_FAILURE)
02697          ast_cli(fd, "Command '%s' failed.\n", s);
02698    }
02699    ast_atomic_fetchadd_int(&e->inuse, -1);
02700 done:
02701    ast_free(duplicate);
02702    return 0;
02703 }
02704 
02705 int ast_cli_command_multiple_full(int uid, int gid, int fd, size_t size, const char *s)
02706 {
02707    char cmd[512];
02708    int x, y = 0, count = 0;
02709 
02710    for (x = 0; x < size; x++) {
02711       cmd[y] = s[x];
02712       y++;
02713       if (s[x] == '\0') {
02714          ast_cli_command_full(uid, gid, fd, cmd);
02715          y = 0;
02716          count++;
02717       }
02718    }
02719    return count;
02720 }