2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Standard Command Line Interface
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include "asterisk/_private.h"
31 #include "asterisk/paths.h" /* use ast_config_AST_MODULE_DIR */
32 #include <sys/signal.h>
37 #include "asterisk/cli.h"
38 #include "asterisk/linkedlists.h"
39 #include "asterisk/module.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/app.h"
44 #include "asterisk/lock.h"
45 #include "editline/readline/readline.h"
46 #include "asterisk/threadstorage.h"
49 * \brief map a debug or verbose value to a filename
51 struct ast_debug_file {
53 AST_RWLIST_ENTRY(ast_debug_file) entry;
57 AST_RWLIST_HEAD(debug_file_list, ast_debug_file);
59 /*! list of filenames and their debug settings */
60 static struct debug_file_list debug_files;
61 /*! list of filenames and their verbose settings */
62 static struct debug_file_list verbose_files;
64 AST_THREADSTORAGE(ast_cli_buf);
66 /*! \brief Initial buffer size for resulting strings in ast_cli() */
67 #define AST_CLI_INITLEN 256
69 void ast_cli(int fd, const char *fmt, ...)
75 if (!(buf = ast_str_thread_get(&ast_cli_buf, AST_CLI_INITLEN)))
79 res = ast_str_set_va(&buf, 0, fmt, ap);
82 if (res != AST_DYNSTR_BUILD_FAILED)
83 ast_carefulwrite(fd, buf->str, strlen(buf->str), 100);
86 unsigned int ast_debug_get_by_file(const char *file)
88 struct ast_debug_file *adf;
91 AST_RWLIST_RDLOCK(&debug_files);
92 AST_LIST_TRAVERSE(&debug_files, adf, entry) {
93 if (!strncasecmp(adf->filename, file, strlen(adf->filename))) {
98 AST_RWLIST_UNLOCK(&debug_files);
103 unsigned int ast_verbose_get_by_file(const char *file)
105 struct ast_debug_file *adf;
106 unsigned int res = 0;
108 AST_RWLIST_RDLOCK(&verbose_files);
109 AST_LIST_TRAVERSE(&verbose_files, adf, entry) {
110 if (!strncasecmp(adf->filename, file, strlen(file))) {
115 AST_RWLIST_UNLOCK(&verbose_files);
120 static AST_RWLIST_HEAD_STATIC(helpers, ast_cli_entry);
122 static char *complete_fn(const char *word, int state)
128 ast_copy_string(filename, word, sizeof(filename));
130 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
132 c = d = filename_completion_function(filename, state);
134 if (c && word[0] != '/')
135 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
143 static char *handle_load(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
145 /* "module load <mod>" */
148 e->command = "module load";
150 "Usage: module load <module name>\n"
151 " Loads the specified module into Asterisk.\n";
155 if (a->pos != e->args)
157 return complete_fn(a->word, a->n);
159 if (a->argc != e->args + 1)
160 return CLI_SHOWUSAGE;
161 if (ast_load_resource(a->argv[e->args])) {
162 ast_cli(a->fd, "Unable to load module %s\n", a->argv[e->args]);
168 static char *handle_load_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
170 char *res = handle_load(e, cmd, a);
176 static char *handle_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
182 e->command = "module reload";
184 "Usage: module reload [module ...]\n"
185 " Reloads configuration files for all listed modules which support\n"
186 " reloading, or for all supported modules if none are listed.\n";
190 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 1);
192 if (a->argc == e->args) {
193 ast_module_reload(NULL);
196 for (x = e->args; x < a->argc; x++) {
197 int res = ast_module_reload(a->argv[x]);
198 /* XXX reload has multiple error returns, including -1 on error and 2 on success */
201 ast_cli(a->fd, "No such module '%s'\n", a->argv[x]);
204 ast_cli(a->fd, "Module '%s' does not support reload\n", a->argv[x]);
211 static char *handle_reload_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
213 char *s = handle_reload(e, cmd, a);
214 if (cmd == CLI_INIT) /* override command name */
215 e->command = "reload";
220 * \brief Find the debug or verbose file setting
221 * \arg debug 1 for debug, 0 for verbose
223 static struct ast_debug_file *find_debug_file(const char *fn, unsigned int debug)
225 struct ast_debug_file *df = NULL;
226 struct debug_file_list *dfl = debug ? &debug_files : &verbose_files;
228 AST_LIST_TRAVERSE(dfl, df, entry) {
229 if (!strcasecmp(df->filename, fn))
236 static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
243 char **argv = a->argv;
246 struct debug_file_list *dfl;
247 struct ast_debug_file *adf;
252 e->command = "core set {debug|verbose} [off|atleast]";
254 "Usage: core set {debug|verbose} [atleast] <level> [filename]\n"
255 " core set {debug|verbose} off\n"
256 " Sets level of debug or verbose messages to be displayed or \n"
257 " sets a filename to display debug messages from.\n"
258 " 0 or off means no messages should be displayed.\n"
259 " Equivalent to -d[d[...]] or -v[v[v...]] on startup\n";
265 /* all the above return, so we proceed with the handler.
266 * we are guaranteed to be called with argc >= e->args;
270 return CLI_SHOWUSAGE;
271 if (!strcasecmp(argv[e->args - 2], "debug")) {
273 oldval = option_debug;
276 dst = &option_verbose;
277 oldval = option_verbose;
280 if (argc == e->args && !strcasecmp(argv[e->args - 1], "off")) {
281 unsigned int debug = (*what == 'C');
284 dfl = debug ? &debug_files : &verbose_files;
286 AST_RWLIST_WRLOCK(dfl);
287 while ((adf = AST_RWLIST_REMOVE_HEAD(dfl, entry)))
289 ast_clear_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
290 AST_RWLIST_UNLOCK(dfl);
294 if (!strcasecmp(argv[e->args-1], "atleast"))
296 if (argc != e->args + atleast && argc != e->args + atleast + 1)
297 return CLI_SHOWUSAGE;
298 if (sscanf(argv[e->args + atleast - 1], "%d", &newlevel) != 1)
299 return CLI_SHOWUSAGE;
300 if (argc == e->args + atleast + 1) {
301 unsigned int debug = (*what == 'C');
302 dfl = debug ? &debug_files : &verbose_files;
304 fn = argv[e->args + atleast];
306 AST_RWLIST_WRLOCK(dfl);
308 if ((adf = find_debug_file(fn, debug)) && !newlevel) {
309 AST_RWLIST_REMOVE(dfl, adf, entry);
310 if (AST_RWLIST_EMPTY(dfl))
311 ast_clear_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
312 AST_RWLIST_UNLOCK(dfl);
313 ast_cli(fd, "%s was %d and has been set to 0 for '%s'\n", what, adf->level, fn);
319 if ((atleast && newlevel < adf->level) || adf->level == newlevel) {
320 ast_cli(fd, "%s is %d for '%s'\n", what, adf->level, fn);
321 AST_RWLIST_UNLOCK(dfl);
324 } else if (!(adf = ast_calloc(1, sizeof(*adf) + strlen(fn) + 1))) {
325 AST_RWLIST_UNLOCK(dfl);
330 adf->level = newlevel;
331 strcpy(adf->filename, fn);
333 ast_set_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
335 AST_RWLIST_INSERT_TAIL(dfl, adf, entry);
336 AST_RWLIST_UNLOCK(dfl);
338 ast_cli(fd, "%s was %d and has been set to %d for '%s'\n", what, oldval, adf->level, adf->filename);
344 if (!atleast || newlevel > *dst)
346 if (oldval > 0 && *dst == 0)
347 ast_cli(fd, "%s is now OFF\n", what);
350 ast_cli(fd, "%s is at least %d\n", what, *dst);
352 ast_cli(fd, "%s was %d and is now %d\n", what, oldval, *dst);
358 static char *handle_logger_mute(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
362 e->command = "logger mute";
364 "Usage: logger mute\n"
365 " Disables logging output to the current console, making it possible to\n"
366 " gather information without being disturbed by scrolling lines.\n";
372 if (a->argc < 2 || a->argc > 3)
373 return CLI_SHOWUSAGE;
375 if (a->argc == 3 && !strcasecmp(a->argv[2], "silent"))
376 ast_console_toggle_mute(a->fd, 1);
378 ast_console_toggle_mute(a->fd, 0);
383 static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
385 /* "module unload mod_1 [mod_2 .. mod_N]" */
387 int force = AST_FORCE_SOFT;
392 e->command = "module unload";
394 "Usage: module unload [-f|-h] <module_1> [<module_2> ... ]\n"
395 " Unloads the specified module from Asterisk. The -f\n"
396 " option causes the module to be unloaded even if it is\n"
397 " in use (may cause a crash) and the -h module causes the\n"
398 " module to be unloaded even if the module says it cannot, \n"
399 " which almost always will cause a crash.\n";
403 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
405 if (a->argc < e->args + 1)
406 return CLI_SHOWUSAGE;
407 x = e->args; /* first argument */
411 force = AST_FORCE_FIRM;
412 else if (s[1] == 'h')
413 force = AST_FORCE_HARD;
415 return CLI_SHOWUSAGE;
416 if (a->argc < e->args + 2) /* need at least one module name */
417 return CLI_SHOWUSAGE;
418 x++; /* skip this argument */
421 for (; x < a->argc; x++) {
422 if (ast_unload_resource(a->argv[x], force)) {
423 ast_cli(a->fd, "Unable to unload resource %s\n", a->argv[x]);
430 static char *handle_unload_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
432 char *res = handle_unload(e, cmd, a);
434 e->command = "unload"; /* XXX override */
438 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
439 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
441 AST_MUTEX_DEFINE_STATIC(climodentrylock);
442 static int climodentryfd = -1;
444 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
446 /* Comparing the like with the module */
447 if (strcasestr(module, like) ) {
448 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
454 static void print_uptimestr(int fd, struct timeval timeval, const char *prefix, int printsec)
456 int x; /* the main part - years, weeks, etc. */
460 #define MINUTE (SECOND*60)
461 #define HOUR (MINUTE*60)
462 #define DAY (HOUR*24)
464 #define YEAR (DAY*365)
465 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
466 if (timeval.tv_sec < 0) /* invalid, nothing to show */
469 if (printsec) { /* plain seconds output */
470 ast_cli(fd, "%s: %lu\n", prefix, (u_long)timeval.tv_sec);
473 out = ast_str_alloca(256);
474 if (timeval.tv_sec > YEAR) {
475 x = (timeval.tv_sec / YEAR);
476 timeval.tv_sec -= (x * YEAR);
477 ast_str_append(&out, 0, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
479 if (timeval.tv_sec > WEEK) {
480 x = (timeval.tv_sec / WEEK);
481 timeval.tv_sec -= (x * WEEK);
482 ast_str_append(&out, 0, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
484 if (timeval.tv_sec > DAY) {
485 x = (timeval.tv_sec / DAY);
486 timeval.tv_sec -= (x * DAY);
487 ast_str_append(&out, 0, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
489 if (timeval.tv_sec > HOUR) {
490 x = (timeval.tv_sec / HOUR);
491 timeval.tv_sec -= (x * HOUR);
492 ast_str_append(&out, 0, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
494 if (timeval.tv_sec > MINUTE) {
495 x = (timeval.tv_sec / MINUTE);
496 timeval.tv_sec -= (x * MINUTE);
497 ast_str_append(&out, 0, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
500 if (x > 0 || out->used == 0) /* if there is nothing, print 0 seconds */
501 ast_str_append(&out, 0, "%d second%s ", x, ESS(x));
502 ast_cli(fd, "%s: %s\n", prefix, out->str);
505 static char * handle_showuptime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
507 struct timeval curtime = ast_tvnow();
512 e->command = "core show uptime [seconds]";
514 "Usage: core show uptime [seconds]\n"
515 " Shows Asterisk uptime information.\n"
516 " The seconds word returns the uptime in seconds only.\n";
522 /* regular handler */
523 if (a->argc == e->args && !strcasecmp(a->argv[e->args-1],"seconds"))
525 else if (a->argc == e->args-1)
528 return CLI_SHOWUSAGE;
529 if (ast_startuptime.tv_sec)
530 print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
531 if (ast_lastreloadtime.tv_sec)
532 print_uptimestr(a->fd, ast_tvsub(curtime, ast_lastreloadtime), "Last reload", printsec);
536 static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
542 e->command = "module show [like]";
544 "Usage: module show [like keyword]\n"
545 " Shows Asterisk modules currently in use, and usage statistics.\n";
549 if (a->pos == e->args)
550 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
554 /* all the above return, so we proceed with the handler.
555 * we are guaranteed to have argc >= e->args
557 if (a->argc == e->args - 1)
559 else if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args-1], "like") )
560 like = a->argv[e->args];
562 return CLI_SHOWUSAGE;
564 ast_mutex_lock(&climodentrylock);
565 climodentryfd = a->fd; /* global, protected by climodentrylock */
566 ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
567 ast_cli(a->fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
569 ast_mutex_unlock(&climodentrylock);
572 #undef MODLIST_FORMAT
573 #undef MODLIST_FORMAT2
575 static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
577 struct timeval curtime = ast_tvnow();
578 int showuptime, printsec;
582 e->command = "core show calls [uptime]";
584 "Usage: core show calls [uptime] [seconds]\n"
585 " Lists number of currently active calls and total number of calls\n"
586 " processed through PBX since last restart. If 'uptime' is specified\n"
587 " the system uptime is also displayed. If 'seconds' is specified in\n"
588 " addition to 'uptime', the system uptime is displayed in seconds.\n";
592 if (a->pos != e->args)
594 return a->n == 0 ? ast_strdup("seconds") : NULL;
597 /* regular handler */
598 if (a->argc >= e->args && !strcasecmp(a->argv[e->args-1],"uptime")) {
601 if (a->argc == e->args+1 && !strcasecmp(a->argv[e->args],"seconds"))
603 else if (a->argc == e->args)
606 return CLI_SHOWUSAGE;
607 } else if (a->argc == e->args-1) {
611 return CLI_SHOWUSAGE;
613 if (option_maxcalls) {
614 ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
615 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
616 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
618 ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
621 ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
623 if (ast_startuptime.tv_sec && showuptime) {
624 print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
627 return RESULT_SUCCESS;
630 static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
632 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
633 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
634 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s!%s\n"
635 #define VERBOSE_FORMAT_STRING "%-20.20s %-20.20s %-16.16s %4d %-7.7s %-12.12s %-25.25s %-15.15s %8.8s %-11.11s %-20.20s\n"
636 #define VERBOSE_FORMAT_STRING2 "%-20.20s %-20.20s %-16.16s %-4.4s %-7.7s %-12.12s %-25.25s %-15.15s %8.8s %-11.11s %-20.20s\n"
638 struct ast_channel *c = NULL;
639 int numchans = 0, concise = 0, verbose = 0, count = 0;
645 e->command = "core show channels [concise|verbose|count]";
647 "Usage: core show channels [concise|verbose|count]\n"
648 " Lists currently defined channels and some information about them. If\n"
649 " 'concise' is specified, the format is abridged and in a more easily\n"
650 " machine parsable format. If 'verbose' is specified, the output includes\n"
651 " more and longer fields. If 'count' is specified only the channel and call\n"
652 " count is output.\n"
653 " The 'concise' option is deprecated and will be removed from future versions\n"
664 if (a->argc == e->args) {
665 if (!strcasecmp(argv[e->args-1],"concise"))
667 else if (!strcasecmp(argv[e->args-1],"verbose"))
669 else if (!strcasecmp(argv[e->args-1],"count"))
672 return CLI_SHOWUSAGE;
673 } else if (a->argc != e->args - 1)
674 return CLI_SHOWUSAGE;
677 if (!concise && !verbose)
678 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
680 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
681 "CallerID", "Duration", "Accountcode", "BridgedTo");
684 while ((c = ast_channel_walk_locked(c)) != NULL) {
685 struct ast_channel *bc = ast_bridged_channel(c);
686 char durbuf[10] = "-";
689 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
690 int duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
692 int durh = duration / 3600;
693 int durm = (duration % 3600) / 60;
694 int durs = duration % 60;
695 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
697 snprintf(durbuf, sizeof(durbuf), "%d", duration);
701 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
702 c->appl ? c->appl : "(None)",
703 S_OR(c->data, ""), /* XXX different from verbose ? */
704 S_OR(c->cid.cid_num, ""),
705 S_OR(c->accountcode, ""),
708 bc ? bc->name : "(None)",
710 } else if (verbose) {
711 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
712 c->appl ? c->appl : "(None)",
713 c->data ? S_OR(c->data, "(Empty)" ): "(None)",
714 S_OR(c->cid.cid_num, ""),
716 S_OR(c->accountcode, ""),
717 bc ? bc->name : "(None)");
719 char locbuf[40] = "(None)";
720 char appdata[40] = "(None)";
722 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
723 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
725 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, S_OR(c->data, ""));
726 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
730 ast_channel_unlock(c);
733 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
735 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
736 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
737 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
739 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
741 ast_cli(fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
746 #undef FORMAT_STRING2
747 #undef CONCISE_FORMAT_STRING
748 #undef VERBOSE_FORMAT_STRING
749 #undef VERBOSE_FORMAT_STRING2
752 static char *handle_softhangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
754 struct ast_channel *c=NULL;
758 e->command = "soft hangup";
760 "Usage: soft hangup <channel>\n"
761 " Request that a channel be hung up. The hangup takes effect\n"
762 " the next time the driver reads or writes from the channel\n";
765 return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
768 return CLI_SHOWUSAGE;
769 c = ast_get_channel_by_name_locked(a->argv[2]);
771 ast_cli(a->fd, "Requested Hangup on channel '%s'\n", c->name);
772 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
773 ast_channel_unlock(c);
775 ast_cli(a->fd, "%s is not a known channel\n", a->argv[2]);
779 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
781 static char *handle_commandmatchesarray(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
791 e->command = "_command matchesarray";
793 "Usage: _command matchesarray \"<line>\" text \n"
794 " This function is used internally to help with command completion and should.\n"
795 " never be called by the user directly.\n";
802 return CLI_SHOWUSAGE;
803 if (!(buf = ast_malloc(buflen)))
806 matches = ast_cli_completion_matches(a->argv[2], a->argv[3]);
808 for (x=0; matches[x]; x++) {
809 matchlen = strlen(matches[x]) + 1;
810 if (len + matchlen >= buflen) {
811 buflen += matchlen * 3;
813 if (!(buf = ast_realloc(obuf, buflen)))
814 /* Memory allocation failure... Just free old buffer and be done */
818 len += sprintf( buf + len, "%s ", matches[x]);
819 ast_free(matches[x]);
826 ast_cli(a->fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
829 ast_cli(a->fd, "NULL\n");
836 static char *handle_commandnummatches(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
842 e->command = "_command nummatches";
844 "Usage: _command nummatches \"<line>\" text \n"
845 " This function is used internally to help with command completion and should.\n"
846 " never be called by the user directly.\n";
853 return CLI_SHOWUSAGE;
855 matches = ast_cli_generatornummatches(a->argv[2], a->argv[3]);
857 ast_cli(a->fd, "%d", matches);
862 static char *handle_commandcomplete(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
867 e->command = "_command complete";
869 "Usage: _command complete \"<line>\" text state\n"
870 " This function is used internally to help with command completion and should.\n"
871 " never be called by the user directly.\n";
877 return CLI_SHOWUSAGE;
878 buf = __ast_cli_generator(a->argv[2], a->argv[3], atoi(a->argv[4]), 0);
883 ast_cli(a->fd, "NULL\n");
887 static char *handle_core_set_debug_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
889 struct ast_channel *c = NULL;
890 int is_all, is_off = 0;
894 e->command = "core set debug channel";
896 "Usage: core set debug channel <all|channel> [off]\n"
897 " Enables/disables debugging on all or on a specific channel.\n";
901 /* XXX remember to handle the optional "off" */
902 if (a->pos != e->args)
904 return a->n == 0 ? ast_strdup("all") : ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
906 /* 'core set debug channel {all|chan_id}' */
907 if (a->argc == e->args + 2) {
908 if (!strcasecmp(a->argv[e->args + 1], "off"))
911 return CLI_SHOWUSAGE;
912 } else if (a->argc != e->args + 1)
913 return CLI_SHOWUSAGE;
915 is_all = !strcasecmp("all", a->argv[e->args]);
918 global_fin &= ~DEBUGCHAN_FLAG;
919 global_fout &= ~DEBUGCHAN_FLAG;
921 global_fin |= DEBUGCHAN_FLAG;
922 global_fout |= DEBUGCHAN_FLAG;
924 c = ast_channel_walk_locked(NULL);
926 c = ast_get_channel_by_name_locked(a->argv[e->args]);
928 ast_cli(a->fd, "No such channel %s\n", a->argv[e->args]);
931 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
933 c->fin &= ~DEBUGCHAN_FLAG;
934 c->fout &= ~DEBUGCHAN_FLAG;
936 c->fin |= DEBUGCHAN_FLAG;
937 c->fout |= DEBUGCHAN_FLAG;
939 ast_cli(a->fd, "Debugging %s on channel %s\n", is_off ? "disabled" : "enabled", c->name);
941 ast_channel_unlock(c);
944 c = ast_channel_walk_locked(c);
946 ast_cli(a->fd, "Debugging on new channels is %s\n", is_off ? "disabled" : "enabled");
950 static char *handle_debugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
954 if (cmd == CLI_HANDLER && a->argc != e->args + 1)
955 return CLI_SHOWUSAGE;
956 res = handle_core_set_debug_channel(e, cmd, a);
958 e->command = "debug channel";
962 static char *handle_nodebugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
965 if (cmd == CLI_HANDLER) {
966 if (a->argc != e->args + 1)
967 return CLI_SHOWUSAGE;
968 /* pretend we have an extra "off" at the end. We can do this as the array
969 * is NULL terminated so we overwrite that entry.
971 a->argv[e->args+1] = "off";
974 res = handle_core_set_debug_channel(e, cmd, a);
976 e->command = "no debug channel";
980 static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
982 struct ast_channel *c=NULL;
984 struct ast_str *out = ast_str_alloca(2048);
986 char nf[256], wf[256], rf[256];
987 long elapsed_seconds=0;
988 int hour=0, min=0, sec=0;
992 e->command = "core show channel";
994 "Usage: core show channel <channel>\n"
995 " Shows lots of information about the specified channel.\n";
998 return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
1002 return CLI_SHOWUSAGE;
1004 c = ast_get_channel_by_name_locked(a->argv[3]);
1006 ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
1010 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
1011 hour = elapsed_seconds / 3600;
1012 min = (elapsed_seconds % 3600) / 60;
1013 sec = elapsed_seconds % 60;
1014 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
1016 strcpy(cdrtime, "N/A");
1023 " Caller ID Name: %s\n"
1024 " DNID Digits: %s\n"
1028 " NativeFormats: %s\n"
1029 " WriteFormat: %s\n"
1031 " WriteTranscode: %s\n"
1032 " ReadTranscode: %s\n"
1033 "1st File Descriptor: %d\n"
1034 " Frames in: %d%s\n"
1035 " Frames out: %d%s\n"
1036 " Time to Hangup: %ld\n"
1037 " Elapsed Time: %s\n"
1038 " Direct Bridge: %s\n"
1039 "Indirect Bridge: %s\n"
1044 " Call Group: %llu\n"
1045 " Pickup Group: %llu\n"
1046 " Application: %s\n"
1048 " Blocking in: %s\n",
1049 c->name, c->tech->type, c->uniqueid,
1050 S_OR(c->cid.cid_num, "(N/A)"),
1051 S_OR(c->cid.cid_name, "(N/A)"),
1052 S_OR(c->cid.cid_dnid, "(N/A)"),
1054 ast_state2str(c->_state), c->_state, c->rings,
1055 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
1056 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
1057 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
1058 c->writetrans ? "Yes" : "No",
1059 c->readtrans ? "Yes" : "No",
1061 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
1062 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
1063 (long)c->whentohangup,
1064 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
1065 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
1066 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
1067 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
1069 if (pbx_builtin_serialize_variables(c, &out))
1070 ast_cli(a->fd," Variables:\n%s\n", out->str);
1071 if (c->cdr && ast_cdr_serialize_variables(c->cdr, &out, '=', '\n', 1))
1072 ast_cli(a->fd," CDR Variables:\n%s\n", out->str);
1074 ast_channel_unlock(c);
1079 * helper function to generate CLI matches from a fixed set of values.
1080 * A NULL word is acceptable.
1082 char *ast_cli_complete(const char *word, char *const choices[], int state)
1084 int i, which = 0, len;
1085 len = ast_strlen_zero(word) ? 0 : strlen(word);
1087 for (i = 0; choices[i]; i++) {
1088 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
1089 return ast_strdup(choices[i]);
1094 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
1096 struct ast_channel *c = NULL;
1099 char notfound = '\0';
1100 char *ret = ¬found; /* so NULL can break the loop */
1105 wordlen = strlen(word);
1107 while (ret == ¬found && (c = ast_channel_walk_locked(c))) {
1108 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
1109 ret = ast_strdup(c->name);
1110 ast_channel_unlock(c);
1112 return ret == ¬found ? NULL : ret;
1115 static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1117 #define FORMAT_STRING "%-25s %-20s %-20s\n"
1119 struct ast_group_info *gi = NULL;
1122 int havepattern = 0;
1126 e->command = "group show channels";
1128 "Usage: group show channels [pattern]\n"
1129 " Lists all currently active channels with channel group(s) specified.\n"
1130 " Optional regular expression pattern is matched to group names for each\n"
1137 if (a->argc < 3 || a->argc > 4)
1138 return CLI_SHOWUSAGE;
1141 if (regcomp(®exbuf, a->argv[3], REG_EXTENDED | REG_NOSUB))
1142 return CLI_SHOWUSAGE;
1146 ast_cli(a->fd, FORMAT_STRING, "Channel", "Group", "Category");
1148 ast_app_group_list_rdlock();
1150 gi = ast_app_group_list_head();
1152 if (!havepattern || !regexec(®exbuf, gi->group, 0, NULL, 0)) {
1153 ast_cli(a->fd, FORMAT_STRING, gi->chan->name, gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category));
1156 gi = AST_LIST_NEXT(gi, list);
1159 ast_app_group_list_unlock();
1164 ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
1166 #undef FORMAT_STRING
1169 static struct ast_cli_entry cli_debug_channel_deprecated = AST_CLI_DEFINE(handle_debugchan_deprecated, "Enable debugging on channel");
1170 static struct ast_cli_entry cli_module_load_deprecated = AST_CLI_DEFINE(handle_load_deprecated, "Load a module");
1171 static struct ast_cli_entry cli_module_reload_deprecated = AST_CLI_DEFINE(handle_reload_deprecated, "reload modules by name");
1172 static struct ast_cli_entry cli_module_unload_deprecated = AST_CLI_DEFINE(handle_unload_deprecated, "unload modules by name");
1174 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1176 static struct ast_cli_entry cli_cli[] = {
1177 /* Deprecated, but preferred command is now consolidated (and already has a deprecated command for it). */
1178 AST_CLI_DEFINE(handle_commandcomplete, "Command complete"),
1179 AST_CLI_DEFINE(handle_commandnummatches, "Returns number of command matches"),
1180 AST_CLI_DEFINE(handle_commandmatchesarray, "Returns command matches array"),
1182 AST_CLI_DEFINE(handle_nodebugchan_deprecated, "Disable debugging on channel(s)"),
1184 AST_CLI_DEFINE(handle_chanlist, "Display information on channels"),
1186 AST_CLI_DEFINE(handle_showcalls, "Display information on calls"),
1188 AST_CLI_DEFINE(handle_showchan, "Display information on a specific channel"),
1190 AST_CLI_DEFINE(handle_core_set_debug_channel, "Enable/disable debugging on a channel",
1191 .deprecate_cmd = &cli_debug_channel_deprecated),
1193 AST_CLI_DEFINE(handle_verbose, "Set level of debug/verbose chattiness"),
1195 AST_CLI_DEFINE(group_show_channels, "Display active channels with group(s)"),
1197 AST_CLI_DEFINE(handle_help, "Display help list, or specific help on a command"),
1199 AST_CLI_DEFINE(handle_logger_mute, "Toggle logging output to a console"),
1201 AST_CLI_DEFINE(handle_modlist, "List modules and info"),
1203 AST_CLI_DEFINE(handle_load, "Load a module by name", .deprecate_cmd = &cli_module_load_deprecated),
1205 AST_CLI_DEFINE(handle_reload, "Reload configuration", .deprecate_cmd = &cli_module_reload_deprecated),
1207 AST_CLI_DEFINE(handle_unload, "Unload a module by name", .deprecate_cmd = &cli_module_unload_deprecated ),
1209 AST_CLI_DEFINE(handle_showuptime, "Show uptime information"),
1211 AST_CLI_DEFINE(handle_softhangup, "Request a hangup on a given channel"),
1215 * Some regexp characters in cli arguments are reserved and used as separators.
1217 static const char cli_rsvd[] = "[]{}|*%";
1220 * initialize the _full_cmd string and related parameters,
1221 * return 0 on success, -1 on error.
1223 static int set_full_cmd(struct ast_cli_entry *e)
1228 ast_join(buf, sizeof(buf), e->cmda);
1229 e->_full_cmd = ast_strdup(buf);
1230 if (!e->_full_cmd) {
1231 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
1234 e->cmdlen = strcspn(e->_full_cmd, cli_rsvd);
1235 for (i = 0; e->cmda[i]; i++)
1241 /*! \brief initialize the _full_cmd string in * each of the builtins. */
1242 void ast_builtins_init(void)
1244 ast_cli_register_multiple(cli_cli, sizeof(cli_cli) / sizeof(struct ast_cli_entry));
1247 static struct ast_cli_entry *cli_next(struct ast_cli_entry *e)
1250 e = AST_LIST_FIRST(&helpers);
1252 e = AST_LIST_NEXT(e, list);
1257 * match a word in the CLI entry.
1258 * returns -1 on mismatch, 0 on match of an optional word,
1259 * 1 on match of a full word.
1261 * The pattern can be
1262 * any_word match for equal
1263 * [foo|bar|baz] optionally, one of these words
1264 * {foo|bar|baz} exactly, one of these words
1267 static int word_match(const char *cmd, const char *cli_word)
1272 if (ast_strlen_zero(cmd) || ast_strlen_zero(cli_word))
1274 if (!strchr(cli_rsvd, cli_word[0])) /* normal match */
1275 return (strcasecmp(cmd, cli_word) == 0) ? 1 : -1;
1276 /* regexp match, takes [foo|bar] or {foo|bar} */
1278 /* wildcard match - will extend in the future */
1279 if (l > 0 && cli_word[0] == '%') {
1280 return 1; /* wildcard */
1282 pos = strcasestr(cli_word, cmd);
1283 if (pos == NULL) /* not found, say ok if optional */
1284 return cli_word[0] == '[' ? 0 : -1;
1285 if (pos == cli_word) /* no valid match at the beginning */
1287 if (strchr(cli_rsvd, pos[-1]) && strchr(cli_rsvd, pos[l]))
1288 return 1; /* valid match */
1289 return -1; /* not found */
1292 /*! \brief if word is a valid prefix for token, returns the pos-th
1293 * match as a malloced string, or NULL otherwise.
1294 * Always tell in *actual how many matches we got.
1296 static char *is_prefix(const char *word, const char *token,
1297 int pos, int *actual)
1303 if (ast_strlen_zero(token))
1305 if (ast_strlen_zero(word))
1306 word = ""; /* dummy */
1308 if (strcspn(word, cli_rsvd) != lw)
1309 return NULL; /* no match if word has reserved chars */
1310 if (strchr(cli_rsvd, token[0]) == NULL) { /* regular match */
1311 if (strncasecmp(token, word, lw)) /* no match */
1314 return (pos != 0) ? NULL : ast_strdup(token);
1316 /* now handle regexp match */
1318 /* Wildcard always matches, so we never do is_prefix on them */
1320 t1 = ast_strdupa(token + 1); /* copy, skipping first char */
1321 while (pos >= 0 && (s = strsep(&t1, cli_rsvd)) && *s) {
1322 if (*s == '%') /* wildcard */
1324 if (strncasecmp(s, word, lw)) /* no match */
1328 return ast_strdup(s);
1334 * \brief locate a cli command in the 'helpers' list (which must be locked).
1335 * exact has 3 values:
1336 * 0 returns if the search key is equal or longer than the entry.
1337 * note that trailing optional arguments are skipped.
1338 * -1 true if the mismatch is on the last word XXX not true!
1339 * 1 true only on complete, exact match.
1341 * The search compares word by word taking care of regexps in e->cmda
1343 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1345 int matchlen = -1; /* length of longest match so far */
1346 struct ast_cli_entry *cand = NULL, *e=NULL;
1348 while ( (e = cli_next(e)) ) {
1349 /* word-by word regexp comparison */
1350 char * const *src = cmds;
1351 char * const *dst = e->cmda;
1353 for (;; dst++, src += n) {
1354 n = word_match(*src, *dst);
1358 if (ast_strlen_zero(*dst) || ((*dst)[0] == '[' && ast_strlen_zero(dst[1]))) {
1359 /* no more words in 'e' */
1360 if (ast_strlen_zero(*src)) /* exact match, cannot do better */
1362 /* Here, cmds has more words than the entry 'e' */
1363 if (match_type != 0) /* but we look for almost exact match... */
1364 continue; /* so we skip this one. */
1365 /* otherwise we like it (case 0) */
1366 } else { /* still words in 'e' */
1367 if (ast_strlen_zero(*src))
1368 continue; /* cmds is shorter than 'e', not good */
1369 /* Here we have leftover words in cmds and 'e',
1370 * but there is a mismatch. We only accept this one if match_type == -1
1371 * and this is the last word for both.
1373 if (match_type != -1 || !ast_strlen_zero(src[1]) ||
1374 !ast_strlen_zero(dst[1])) /* not the one we look for */
1376 /* good, we are in case match_type == -1 and mismatch on last word */
1378 if (src - cmds > matchlen) { /* remember the candidate */
1379 matchlen = src - cmds;
1383 return e ? e : cand;
1386 static char *find_best(char *argv[])
1388 static char cmdline[80];
1390 /* See how close we get, then print the candidate */
1391 char *myargv[AST_MAX_CMD_LEN];
1392 for (x=0;x<AST_MAX_CMD_LEN;x++)
1394 AST_RWLIST_RDLOCK(&helpers);
1395 for (x=0;argv[x];x++) {
1396 myargv[x] = argv[x];
1397 if (!find_cli(myargv, -1))
1400 AST_RWLIST_UNLOCK(&helpers);
1401 ast_join(cmdline, sizeof(cmdline), myargv);
1405 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1407 if (e->deprecate_cmd) {
1408 __ast_cli_unregister(e->deprecate_cmd, e);
1411 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1413 AST_RWLIST_WRLOCK(&helpers);
1414 AST_RWLIST_REMOVE(&helpers, e, list);
1415 AST_RWLIST_UNLOCK(&helpers);
1416 ast_free(e->_full_cmd);
1417 e->_full_cmd = NULL;
1419 /* this is a new-style entry. Reset fields and free memory. */
1420 bzero((char **)(e->cmda), sizeof(e->cmda));
1421 ast_free(e->command);
1429 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1431 struct ast_cli_entry *cur;
1432 int i, lf, ret = -1;
1434 struct ast_cli_args a; /* fake argument */
1435 char **dst = (char **)e->cmda; /* need to cast as the entry is readonly */
1438 bzero (&a, sizeof(a));
1439 e->handler(e, CLI_INIT, &a);
1440 /* XXX check that usage and command are filled up */
1441 s = ast_skip_blanks(e->command);
1442 s = e->command = ast_strdup(s);
1443 for (i=0; !ast_strlen_zero(s) && i < AST_MAX_CMD_LEN-1; i++) {
1444 *dst++ = s; /* store string */
1445 s = ast_skip_nonblanks(s);
1446 if (*s == '\0') /* we are done */
1449 s = ast_skip_blanks(s);
1453 AST_RWLIST_WRLOCK(&helpers);
1455 if (find_cli(e->cmda, 1)) {
1456 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", e->_full_cmd);
1459 if (set_full_cmd(e))
1465 e->summary = ed->summary;
1466 e->usage = ed->usage;
1467 /* XXX If command A deprecates command B, and command B deprecates command C...
1468 Do we want to show command A or command B when telling the user to use new syntax?
1469 This currently would show command A.
1470 To show command B, you just need to always use ed->_full_cmd.
1472 e->_deprecated_by = S_OR(ed->_deprecated_by, ed->_full_cmd);
1476 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1477 int len = cur->cmdlen;
1480 if (strncasecmp(e->_full_cmd, cur->_full_cmd, len) < 0) {
1481 AST_RWLIST_INSERT_BEFORE_CURRENT(e, list);
1485 AST_RWLIST_TRAVERSE_SAFE_END;
1488 AST_RWLIST_INSERT_TAIL(&helpers, e, list);
1489 ret = 0; /* success */
1492 AST_RWLIST_UNLOCK(&helpers);
1494 if (e->deprecate_cmd) {
1495 /* This command deprecates another command. Register that one also. */
1496 __ast_cli_register(e->deprecate_cmd, e);
1502 /* wrapper function, so we can unregister deprecated commands recursively */
1503 int ast_cli_unregister(struct ast_cli_entry *e)
1505 return __ast_cli_unregister(e, NULL);
1508 /* wrapper function, so we can register deprecated commands recursively */
1509 int ast_cli_register(struct ast_cli_entry *e)
1511 return __ast_cli_register(e, NULL);
1515 * register/unregister an array of entries.
1517 int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1521 for (i = 0; i < len; i++)
1522 res |= ast_cli_register(e + i);
1527 int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1531 for (i = 0; i < len; i++)
1532 res |= ast_cli_unregister(e + i);
1538 /*! \brief helper for final part of
1539 * handle_help. if locked = 0 it's just "help_workhorse",
1540 * otherwise assume the list is already locked and print
1541 * an error message if not found.
1543 static char *help1(int fd, char *match[], int locked)
1545 char matchstr[80] = "";
1546 struct ast_cli_entry *e = NULL;
1551 ast_join(matchstr, sizeof(matchstr), match);
1552 len = strlen(matchstr);
1555 AST_RWLIST_RDLOCK(&helpers);
1556 while ( (e = cli_next(e)) ) {
1557 /* Hide commands that start with '_' */
1558 if (e->_full_cmd[0] == '_')
1560 /* Hide commands that are marked as deprecated. */
1563 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1565 ast_cli(fd, "%30.30s %s\n", e->_full_cmd, S_OR(e->summary, "<no description available>"));
1569 AST_RWLIST_UNLOCK(&helpers);
1570 if (!locked && !found && matchstr[0])
1571 ast_cli(fd, "No such command '%s'.\n", matchstr);
1575 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1578 struct ast_cli_entry *my_e;
1580 if (cmd == CLI_INIT) {
1581 e->command = "help";
1583 "Usage: help [topic]\n"
1584 " When called with a topic as an argument, displays usage\n"
1585 " information on the given command. If called without a\n"
1586 " topic, it provides a list of commands.\n";
1589 } else if (cmd == CLI_GENERATE) {
1590 /* skip first 4 or 5 chars, "help " */
1591 int l = strlen(a->line);
1595 /* XXX watch out, should stop to the non-generator parts */
1596 return __ast_cli_generator(a->line + l, a->word, a->n, 0);
1599 return help1(a->fd, NULL, 0);
1601 AST_RWLIST_RDLOCK(&helpers);
1602 my_e = find_cli(a->argv + 1, 1); /* try exact match first */
1604 return help1(a->fd, a->argv + 1, 1 /* locked */);
1606 ast_cli(a->fd, "%s", my_e->usage);
1608 ast_join(fullcmd, sizeof(fullcmd), a->argv+1);
1609 ast_cli(a->fd, "No help text available for '%s'.\n", fullcmd);
1611 AST_RWLIST_UNLOCK(&helpers);
1615 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1624 if (trailingwhitespace == NULL)
1625 trailingwhitespace = &dummy;
1626 *trailingwhitespace = 0;
1627 if (s == NULL) /* invalid, though! */
1629 /* make a copy to store the parsed string */
1630 if (!(dup = ast_strdup(s)))
1634 /* scan the original string copying into cur when needed */
1637 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1640 if (*s == '"' && !escaped) {
1642 if (quoted && whitespace) {
1643 /* start a quoted string from previous whitespace: new argument */
1647 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1648 /* If we are not already in whitespace, and not in a quoted string or
1649 processing an escape sequence, and just entered whitespace, then
1650 finalize the previous argument and remember that we are in whitespace
1656 } else if (*s == '\\' && !escaped) {
1660 /* we leave whitespace, and are not quoted. So it's a new argument */
1668 /* Null terminate */
1670 /* XXX put a NULL in the last argument, because some functions that take
1671 * the array may want a null-terminated array.
1672 * argc still reflects the number of non-NULL entries.
1676 *trailingwhitespace = whitespace;
1680 /*! \brief Return the number of unique matches for the generator */
1681 int ast_cli_generatornummatches(const char *text, const char *word)
1683 int matches = 0, i = 0;
1684 char *buf = NULL, *oldbuf = NULL;
1686 while ((buf = ast_cli_generator(text, word, i++))) {
1687 if (!oldbuf || strcmp(buf,oldbuf))
1698 char **ast_cli_completion_matches(const char *text, const char *word)
1700 char **match_list = NULL, *retstr, *prevstr;
1701 size_t match_list_len, max_equal, which, i;
1704 /* leave entry 0 free for the longest common substring */
1706 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1707 if (matches + 1 >= match_list_len) {
1708 match_list_len <<= 1;
1709 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1712 match_list[++matches] = retstr;
1716 return match_list; /* NULL */
1718 /* Find the longest substring that is common to all results
1719 * (it is a candidate for completion), and store a copy in entry 0.
1721 prevstr = match_list[1];
1722 max_equal = strlen(prevstr);
1723 for (which = 2; which <= matches; which++) {
1724 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1729 if (!(retstr = ast_malloc(max_equal + 1)))
1732 ast_copy_string(retstr, match_list[1], max_equal + 1);
1733 match_list[0] = retstr;
1735 /* ensure that the array is NULL terminated */
1736 if (matches + 1 >= match_list_len) {
1737 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1740 match_list[matches + 1] = NULL;
1745 /*! \brief returns true if there are more words to match */
1746 static int more_words (char * const *dst)
1749 for (i = 0; dst[i]; i++) {
1750 if (dst[i][0] != '[')
1757 * generate the entry at position 'state'
1759 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1761 char *argv[AST_MAX_ARGS];
1762 struct ast_cli_entry *e = NULL;
1763 int x = 0, argindex, matchlen;
1766 char matchstr[80] = "";
1768 /* Split the argument into an array of words */
1769 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1771 if (!dup) /* malloc error */
1774 /* Compute the index of the last argument (could be an empty string) */
1775 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1777 /* rebuild the command, ignore terminating white space and flatten space */
1778 ast_join(matchstr, sizeof(matchstr)-1, argv);
1779 matchlen = strlen(matchstr);
1781 strcat(matchstr, " "); /* XXX */
1786 AST_RWLIST_RDLOCK(&helpers);
1787 while ( (e = cli_next(e)) ) {
1788 /* XXX repeated code */
1789 int src = 0, dst = 0, n = 0;
1791 if (e->command[0] == '_')
1795 * Try to match words, up to and excluding the last word, which
1796 * is either a blank or something that we want to extend.
1798 for (;src < argindex; dst++, src += n) {
1799 n = word_match(argv[src], e->cmda[dst]);
1804 if (src != argindex && more_words(e->cmda + dst)) /* not a match */
1806 ret = is_prefix(argv[src], e->cmda[dst], state - matchnum, &n);
1807 matchnum += n; /* this many matches here */
1810 * argv[src] is a valid prefix of the next word in this
1811 * command. If this is also the correct entry, return it.
1813 if (matchnum > state)
1817 } else if (ast_strlen_zero(e->cmda[dst])) {
1819 * This entry is a prefix of the command string entered
1820 * (only one entry in the list should have this property).
1821 * Run the generator if one is available. In any case we are done.
1823 if (e->handler) { /* new style command */
1824 struct ast_cli_args a = {
1825 .line = matchstr, .word = word,
1827 .n = state - matchnum };
1828 ret = e->handler(e, CLI_GENERATE, &a);
1835 AST_RWLIST_UNLOCK(&helpers);
1840 char *ast_cli_generator(const char *text, const char *word, int state)
1842 return __ast_cli_generator(text, word, state, 1);
1845 int ast_cli_command(int fd, const char *s)
1847 char *args[AST_MAX_ARGS + 1];
1848 struct ast_cli_entry *e;
1850 char *dup = parse_args(s, &x, args + 1, AST_MAX_ARGS, NULL);
1851 char *retval = NULL;
1852 struct ast_cli_args a = {
1853 .fd = fd, .argc = x, .argv = args+1 };
1858 if (x < 1) /* We need at least one entry, otherwise ignore */
1861 AST_RWLIST_RDLOCK(&helpers);
1862 e = find_cli(args + 1, 0);
1864 ast_atomic_fetchadd_int(&e->inuse, 1);
1865 AST_RWLIST_UNLOCK(&helpers);
1867 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(args + 1));
1871 * Within the handler, argv[-1] contains a pointer to the ast_cli_entry.
1872 * Remember that the array returned by parse_args is NULL-terminated.
1874 args[0] = (char *)e;
1876 retval = e->handler(e, CLI_HANDLER, &a);
1878 if (retval == CLI_SHOWUSAGE) {
1879 ast_cli(fd, "%s", S_OR(e->usage, "Invalid usage, but no usage information available.\n"));
1880 AST_RWLIST_RDLOCK(&helpers);
1882 ast_cli(fd, "The '%s' command is deprecated and will be removed in a future release. Please use '%s' instead.\n", e->_full_cmd, e->_deprecated_by);
1883 AST_RWLIST_UNLOCK(&helpers);
1885 if (retval == CLI_FAILURE)
1886 ast_cli(fd, "Command '%s' failed.\n", s);
1887 AST_RWLIST_RDLOCK(&helpers);
1888 if (e->deprecated == 1) {
1889 ast_cli(fd, "The '%s' command is deprecated and will be removed in a future release. Please use '%s' instead.\n", e->_full_cmd, e->_deprecated_by);
1892 AST_RWLIST_UNLOCK(&helpers);
1894 ast_atomic_fetchadd_int(&e->inuse, -1);
1900 int ast_cli_command_multiple(int fd, size_t size, const char *s)
1903 int x, y = 0, count = 0;
1905 for (x = 0; x < size; x++) {
1909 ast_cli_command(fd, cmd);