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 /* XXX the following function is not reentrant, so we better not use it */
133 c = filename_completion_function(filename, state);
135 if (c && word[0] != '/')
136 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
138 return c ? ast_strdup(c) : c;
141 static char *handle_load(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
143 /* "module load <mod>" */
146 e->command = "module load";
148 "Usage: module load <module name>\n"
149 " Loads the specified module into Asterisk.\n";
153 if (a->pos != e->args)
155 return complete_fn(a->word, a->n);
157 if (a->argc != e->args + 1)
158 return CLI_SHOWUSAGE;
159 if (ast_load_resource(a->argv[e->args])) {
160 ast_cli(a->fd, "Unable to load module %s\n", a->argv[e->args]);
166 static char *handle_load_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
168 char *res = handle_load(e, cmd, a);
174 static char *handle_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
180 e->command = "module reload";
182 "Usage: module reload [module ...]\n"
183 " Reloads configuration files for all listed modules which support\n"
184 " reloading, or for all supported modules if none are listed.\n";
188 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 1);
190 if (a->argc == e->args) {
191 ast_module_reload(NULL);
194 for (x = e->args; x < a->argc; x++) {
195 int res = ast_module_reload(a->argv[x]);
196 /* XXX reload has multiple error returns, including -1 on error and 2 on success */
199 ast_cli(a->fd, "No such module '%s'\n", a->argv[x]);
202 ast_cli(a->fd, "Module '%s' does not support reload\n", a->argv[x]);
209 static char *handle_reload_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
211 char *s = handle_reload(e, cmd, a);
212 if (cmd == CLI_INIT) /* override command name */
213 e->command = "reload";
218 * \brief Find the debug or verbose file setting
219 * \arg debug 1 for debug, 0 for verbose
221 static struct ast_debug_file *find_debug_file(const char *fn, unsigned int debug)
223 struct ast_debug_file *df = NULL;
224 struct debug_file_list *dfl = debug ? &debug_files : &verbose_files;
226 AST_LIST_TRAVERSE(dfl, df, entry) {
227 if (!strcasecmp(df->filename, fn))
234 static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
241 char **argv = a->argv;
244 struct debug_file_list *dfl;
245 struct ast_debug_file *adf;
250 e->command = "core set {debug|verbose} [off|atleast]";
252 "Usage: core set {debug|verbose} [atleast] <level> [filename]\n"
253 " core set {debug|verbose} off\n"
254 " Sets level of debug or verbose messages to be displayed or \n"
255 " sets a filename to display debug messages from.\n"
256 " 0 or off means no messages should be displayed.\n"
257 " Equivalent to -d[d[...]] or -v[v[v...]] on startup\n";
263 /* all the above return, so we proceed with the handler.
264 * we are guaranteed to be called with argc >= e->args;
268 return CLI_SHOWUSAGE;
269 if (!strcasecmp(argv[e->args - 2], "debug")) {
271 oldval = option_debug;
274 dst = &option_verbose;
275 oldval = option_verbose;
278 if (argc == e->args && !strcasecmp(argv[e->args - 1], "off")) {
279 unsigned int debug = (*what == 'C');
282 dfl = debug ? &debug_files : &verbose_files;
284 AST_RWLIST_WRLOCK(dfl);
285 while ((adf = AST_RWLIST_REMOVE_HEAD(dfl, entry)))
287 ast_clear_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
288 AST_RWLIST_UNLOCK(dfl);
292 if (!strcasecmp(argv[e->args-1], "atleast"))
294 if (argc != e->args + atleast && argc != e->args + atleast + 1)
295 return CLI_SHOWUSAGE;
296 if (sscanf(argv[e->args + atleast - 1], "%d", &newlevel) != 1)
297 return CLI_SHOWUSAGE;
298 if (argc == e->args + atleast + 1) {
299 unsigned int debug = (*what == 'C');
300 dfl = debug ? &debug_files : &verbose_files;
302 fn = argv[e->args + atleast];
304 AST_RWLIST_WRLOCK(dfl);
306 if ((adf = find_debug_file(fn, debug)) && !newlevel) {
307 AST_RWLIST_REMOVE(dfl, adf, entry);
308 if (AST_RWLIST_EMPTY(dfl))
309 ast_clear_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
310 AST_RWLIST_UNLOCK(dfl);
311 ast_cli(fd, "%s was %d and has been set to 0 for '%s'\n", what, adf->level, fn);
317 if ((atleast && newlevel < adf->level) || adf->level == newlevel) {
318 ast_cli(fd, "%s is %d for '%s'\n", what, adf->level, fn);
319 AST_RWLIST_UNLOCK(dfl);
322 } else if (!(adf = ast_calloc(1, sizeof(*adf) + strlen(fn) + 1))) {
323 AST_RWLIST_UNLOCK(dfl);
328 adf->level = newlevel;
329 strcpy(adf->filename, fn);
331 ast_set_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
333 AST_RWLIST_INSERT_TAIL(dfl, adf, entry);
334 AST_RWLIST_UNLOCK(dfl);
336 ast_cli(fd, "%s was %d and has been set to %d for '%s'\n", what, oldval, adf->level, adf->filename);
342 if (!atleast || newlevel > *dst)
344 if (oldval > 0 && *dst == 0)
345 ast_cli(fd, "%s is now OFF\n", what);
348 ast_cli(fd, "%s is at least %d\n", what, *dst);
350 ast_cli(fd, "%s was %d and is now %d\n", what, oldval, *dst);
356 static char *handle_logger_mute(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
360 e->command = "logger mute";
362 "Usage: logger mute\n"
363 " Disables logging output to the current console, making it possible to\n"
364 " gather information without being disturbed by scrolling lines.\n";
370 if (a->argc < 2 || a->argc > 3)
371 return CLI_SHOWUSAGE;
373 if (a->argc == 3 && !strcasecmp(a->argv[2], "silent"))
374 ast_console_toggle_mute(a->fd, 1);
376 ast_console_toggle_mute(a->fd, 0);
381 static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
383 /* "module unload mod_1 [mod_2 .. mod_N]" */
385 int force = AST_FORCE_SOFT;
390 e->command = "module unload";
392 "Usage: module unload [-f|-h] <module_1> [<module_2> ... ]\n"
393 " Unloads the specified module from Asterisk. The -f\n"
394 " option causes the module to be unloaded even if it is\n"
395 " in use (may cause a crash) and the -h module causes the\n"
396 " module to be unloaded even if the module says it cannot, \n"
397 " which almost always will cause a crash.\n";
401 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
403 if (a->argc < e->args + 1)
404 return CLI_SHOWUSAGE;
405 x = e->args; /* first argument */
409 force = AST_FORCE_FIRM;
410 else if (s[1] == 'h')
411 force = AST_FORCE_HARD;
413 return CLI_SHOWUSAGE;
414 if (a->argc < e->args + 2) /* need at least one module name */
415 return CLI_SHOWUSAGE;
416 x++; /* skip this argument */
419 for (; x < a->argc; x++) {
420 if (ast_unload_resource(a->argv[x], force)) {
421 ast_cli(a->fd, "Unable to unload resource %s\n", a->argv[x]);
428 static char *handle_unload_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
430 char *res = handle_unload(e, cmd, a);
432 e->command = "unload"; /* XXX override */
436 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
437 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
439 AST_MUTEX_DEFINE_STATIC(climodentrylock);
440 static int climodentryfd = -1;
442 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
444 /* Comparing the like with the module */
445 if (strcasestr(module, like) ) {
446 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
452 static void print_uptimestr(int fd, struct timeval timeval, const char *prefix, int printsec)
454 int x; /* the main part - years, weeks, etc. */
458 #define MINUTE (SECOND*60)
459 #define HOUR (MINUTE*60)
460 #define DAY (HOUR*24)
462 #define YEAR (DAY*365)
463 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
464 if (timeval.tv_sec < 0) /* invalid, nothing to show */
467 if (printsec) { /* plain seconds output */
468 ast_cli(fd, "%s: %lu\n", prefix, (u_long)timeval.tv_sec);
471 out = ast_str_alloca(256);
472 if (timeval.tv_sec > YEAR) {
473 x = (timeval.tv_sec / YEAR);
474 timeval.tv_sec -= (x * YEAR);
475 ast_str_append(&out, 0, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
477 if (timeval.tv_sec > WEEK) {
478 x = (timeval.tv_sec / WEEK);
479 timeval.tv_sec -= (x * WEEK);
480 ast_str_append(&out, 0, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
482 if (timeval.tv_sec > DAY) {
483 x = (timeval.tv_sec / DAY);
484 timeval.tv_sec -= (x * DAY);
485 ast_str_append(&out, 0, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
487 if (timeval.tv_sec > HOUR) {
488 x = (timeval.tv_sec / HOUR);
489 timeval.tv_sec -= (x * HOUR);
490 ast_str_append(&out, 0, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
492 if (timeval.tv_sec > MINUTE) {
493 x = (timeval.tv_sec / MINUTE);
494 timeval.tv_sec -= (x * MINUTE);
495 ast_str_append(&out, 0, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
498 if (x > 0 || out->used == 0) /* if there is nothing, print 0 seconds */
499 ast_str_append(&out, 0, "%d second%s ", x, ESS(x));
500 ast_cli(fd, "%s: %s\n", prefix, out->str);
503 static char * handle_showuptime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
505 struct timeval curtime = ast_tvnow();
510 e->command = "core show uptime [seconds]";
512 "Usage: core show uptime [seconds]\n"
513 " Shows Asterisk uptime information.\n"
514 " The seconds word returns the uptime in seconds only.\n";
520 /* regular handler */
521 if (a->argc == e->args && !strcasecmp(a->argv[e->args-1],"seconds"))
523 else if (a->argc == e->args-1)
526 return CLI_SHOWUSAGE;
527 if (ast_startuptime.tv_sec)
528 print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
529 if (ast_lastreloadtime.tv_sec)
530 print_uptimestr(a->fd, ast_tvsub(curtime, ast_lastreloadtime), "Last reload", printsec);
534 static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
540 e->command = "module show [like]";
542 "Usage: module show [like keyword]\n"
543 " Shows Asterisk modules currently in use, and usage statistics.\n";
547 if (a->pos == e->args)
548 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
552 /* all the above return, so we proceed with the handler.
553 * we are guaranteed to have argc >= e->args
555 if (a->argc == e->args - 1)
557 else if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args-1], "like") )
558 like = a->argv[e->args];
560 return CLI_SHOWUSAGE;
562 ast_mutex_lock(&climodentrylock);
563 climodentryfd = a->fd; /* global, protected by climodentrylock */
564 ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
565 ast_cli(a->fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
567 ast_mutex_unlock(&climodentrylock);
570 #undef MODLIST_FORMAT
571 #undef MODLIST_FORMAT2
573 static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
575 struct timeval curtime = ast_tvnow();
576 int showuptime, printsec;
580 e->command = "core show calls [uptime]";
582 "Usage: core show calls [uptime] [seconds]\n"
583 " Lists number of currently active calls and total number of calls\n"
584 " processed through PBX since last restart. If 'uptime' is specified\n"
585 " the system uptime is also displayed. If 'seconds' is specified in\n"
586 " addition to 'uptime', the system uptime is displayed in seconds.\n";
590 if (a->pos != e->args)
592 return a->n == 0 ? ast_strdup("seconds") : NULL;
595 /* regular handler */
596 if (a->argc >= e->args && !strcasecmp(a->argv[e->args-1],"uptime")) {
599 if (a->argc == e->args+1 && !strcasecmp(a->argv[e->args],"seconds"))
601 else if (a->argc == e->args)
604 return CLI_SHOWUSAGE;
605 } else if (a->argc == e->args-1) {
609 return CLI_SHOWUSAGE;
611 if (option_maxcalls) {
612 ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
613 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
614 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
616 ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
619 ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
621 if (ast_startuptime.tv_sec && showuptime) {
622 print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
625 return RESULT_SUCCESS;
628 static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
630 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
631 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
632 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s!%s\n"
633 #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"
634 #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"
636 struct ast_channel *c = NULL;
637 int numchans = 0, concise = 0, verbose = 0, count = 0;
643 e->command = "core show channels [concise|verbose|count]";
645 "Usage: core show channels [concise|verbose|count]\n"
646 " Lists currently defined channels and some information about them. If\n"
647 " 'concise' is specified, the format is abridged and in a more easily\n"
648 " machine parsable format. If 'verbose' is specified, the output includes\n"
649 " more and longer fields. If 'count' is specified only the channel and call\n"
650 " count is output.\n"
651 " The 'concise' option is deprecated and will be removed from future versions\n"
662 if (a->argc == e->args) {
663 if (!strcasecmp(argv[e->args-1],"concise"))
665 else if (!strcasecmp(argv[e->args-1],"verbose"))
667 else if (!strcasecmp(argv[e->args-1],"count"))
670 return CLI_SHOWUSAGE;
671 } else if (a->argc != e->args - 1)
672 return CLI_SHOWUSAGE;
675 if (!concise && !verbose)
676 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
678 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
679 "CallerID", "Duration", "Accountcode", "BridgedTo");
682 while ((c = ast_channel_walk_locked(c)) != NULL) {
683 struct ast_channel *bc = ast_bridged_channel(c);
684 char durbuf[10] = "-";
687 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
688 int duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
690 int durh = duration / 3600;
691 int durm = (duration % 3600) / 60;
692 int durs = duration % 60;
693 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
695 snprintf(durbuf, sizeof(durbuf), "%d", duration);
699 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
700 c->appl ? c->appl : "(None)",
701 S_OR(c->data, ""), /* XXX different from verbose ? */
702 S_OR(c->cid.cid_num, ""),
703 S_OR(c->accountcode, ""),
706 bc ? bc->name : "(None)",
708 } else if (verbose) {
709 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
710 c->appl ? c->appl : "(None)",
711 c->data ? S_OR(c->data, "(Empty)" ): "(None)",
712 S_OR(c->cid.cid_num, ""),
714 S_OR(c->accountcode, ""),
715 bc ? bc->name : "(None)");
717 char locbuf[40] = "(None)";
718 char appdata[40] = "(None)";
720 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
721 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
723 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, S_OR(c->data, ""));
724 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
728 ast_channel_unlock(c);
731 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
733 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
734 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
735 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
737 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
739 ast_cli(fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
744 #undef FORMAT_STRING2
745 #undef CONCISE_FORMAT_STRING
746 #undef VERBOSE_FORMAT_STRING
747 #undef VERBOSE_FORMAT_STRING2
750 static char *handle_softhangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
752 struct ast_channel *c=NULL;
756 e->command = "soft hangup";
758 "Usage: soft hangup <channel>\n"
759 " Request that a channel be hung up. The hangup takes effect\n"
760 " the next time the driver reads or writes from the channel\n";
763 return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
766 return CLI_SHOWUSAGE;
767 c = ast_get_channel_by_name_locked(a->argv[2]);
769 ast_cli(a->fd, "Requested Hangup on channel '%s'\n", c->name);
770 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
771 ast_channel_unlock(c);
773 ast_cli(a->fd, "%s is not a known channel\n", a->argv[2]);
777 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
779 static char *handle_commandmatchesarray(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
789 e->command = "_command matchesarray";
791 "Usage: _command matchesarray \"<line>\" text \n"
792 " This function is used internally to help with command completion and should.\n"
793 " never be called by the user directly.\n";
800 return CLI_SHOWUSAGE;
801 if (!(buf = ast_malloc(buflen)))
804 matches = ast_cli_completion_matches(a->argv[2], a->argv[3]);
806 for (x=0; matches[x]; x++) {
807 matchlen = strlen(matches[x]) + 1;
808 if (len + matchlen >= buflen) {
809 buflen += matchlen * 3;
811 if (!(buf = ast_realloc(obuf, buflen)))
812 /* Memory allocation failure... Just free old buffer and be done */
816 len += sprintf( buf + len, "%s ", matches[x]);
817 ast_free(matches[x]);
824 ast_cli(a->fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
827 ast_cli(a->fd, "NULL\n");
834 static char *handle_commandnummatches(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
840 e->command = "_command nummatches";
842 "Usage: _command nummatches \"<line>\" text \n"
843 " This function is used internally to help with command completion and should.\n"
844 " never be called by the user directly.\n";
851 return CLI_SHOWUSAGE;
853 matches = ast_cli_generatornummatches(a->argv[2], a->argv[3]);
855 ast_cli(a->fd, "%d", matches);
860 static char *handle_commandcomplete(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
865 e->command = "_command complete";
867 "Usage: _command complete \"<line>\" text state\n"
868 " This function is used internally to help with command completion and should.\n"
869 " never be called by the user directly.\n";
875 return CLI_SHOWUSAGE;
876 buf = __ast_cli_generator(a->argv[2], a->argv[3], atoi(a->argv[4]), 0);
881 ast_cli(a->fd, "NULL\n");
885 static char *handle_core_set_debug_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
887 struct ast_channel *c = NULL;
888 int is_all, is_off = 0;
892 e->command = "core set debug channel";
894 "Usage: core set debug channel <all|channel> [off]\n"
895 " Enables/disables debugging on all or on a specific channel.\n";
899 /* XXX remember to handle the optional "off" */
900 if (a->pos != e->args)
902 return a->n == 0 ? ast_strdup("all") : ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
904 /* 'core set debug channel {all|chan_id}' */
905 if (a->argc == e->args + 2) {
906 if (!strcasecmp(a->argv[e->args + 1], "off"))
909 return CLI_SHOWUSAGE;
910 } else if (a->argc != e->args + 1)
911 return CLI_SHOWUSAGE;
913 is_all = !strcasecmp("all", a->argv[e->args]);
916 global_fin &= ~DEBUGCHAN_FLAG;
917 global_fout &= ~DEBUGCHAN_FLAG;
919 global_fin |= DEBUGCHAN_FLAG;
920 global_fout |= DEBUGCHAN_FLAG;
922 c = ast_channel_walk_locked(NULL);
924 c = ast_get_channel_by_name_locked(a->argv[e->args]);
926 ast_cli(a->fd, "No such channel %s\n", a->argv[e->args]);
929 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
931 c->fin &= ~DEBUGCHAN_FLAG;
932 c->fout &= ~DEBUGCHAN_FLAG;
934 c->fin |= DEBUGCHAN_FLAG;
935 c->fout |= DEBUGCHAN_FLAG;
937 ast_cli(a->fd, "Debugging %s on channel %s\n", is_off ? "disabled" : "enabled", c->name);
939 ast_channel_unlock(c);
942 c = ast_channel_walk_locked(c);
944 ast_cli(a->fd, "Debugging on new channels is %s\n", is_off ? "disabled" : "enabled");
948 static char *handle_debugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
952 if (cmd == CLI_HANDLER && a->argc != e->args + 1)
953 return CLI_SHOWUSAGE;
954 res = handle_core_set_debug_channel(e, cmd, a);
956 e->command = "debug channel";
960 static char *handle_nodebugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
963 if (cmd == CLI_HANDLER) {
964 if (a->argc != e->args + 1)
965 return CLI_SHOWUSAGE;
966 /* pretend we have an extra "off" at the end. We can do this as the array
967 * is NULL terminated so we overwrite that entry.
969 a->argv[e->args+1] = "off";
972 res = handle_core_set_debug_channel(e, cmd, a);
974 e->command = "no debug channel";
978 static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
980 struct ast_channel *c=NULL;
982 struct ast_str *out = ast_str_alloca(2048);
984 char nf[256], wf[256], rf[256];
985 long elapsed_seconds=0;
986 int hour=0, min=0, sec=0;
990 e->command = "core show channel";
992 "Usage: core show channel <channel>\n"
993 " Shows lots of information about the specified channel.\n";
996 return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
1000 return CLI_SHOWUSAGE;
1002 c = ast_get_channel_by_name_locked(a->argv[3]);
1004 ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
1008 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
1009 hour = elapsed_seconds / 3600;
1010 min = (elapsed_seconds % 3600) / 60;
1011 sec = elapsed_seconds % 60;
1012 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
1014 strcpy(cdrtime, "N/A");
1021 " Caller ID Name: %s\n"
1022 " DNID Digits: %s\n"
1026 " NativeFormats: %s\n"
1027 " WriteFormat: %s\n"
1029 " WriteTranscode: %s\n"
1030 " ReadTranscode: %s\n"
1031 "1st File Descriptor: %d\n"
1032 " Frames in: %d%s\n"
1033 " Frames out: %d%s\n"
1034 " Time to Hangup: %ld\n"
1035 " Elapsed Time: %s\n"
1036 " Direct Bridge: %s\n"
1037 "Indirect Bridge: %s\n"
1042 " Call Group: %llu\n"
1043 " Pickup Group: %llu\n"
1044 " Application: %s\n"
1046 " Blocking in: %s\n",
1047 c->name, c->tech->type, c->uniqueid,
1048 S_OR(c->cid.cid_num, "(N/A)"),
1049 S_OR(c->cid.cid_name, "(N/A)"),
1050 S_OR(c->cid.cid_dnid, "(N/A)"),
1052 ast_state2str(c->_state), c->_state, c->rings,
1053 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
1054 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
1055 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
1056 c->writetrans ? "Yes" : "No",
1057 c->readtrans ? "Yes" : "No",
1059 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
1060 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
1061 (long)c->whentohangup,
1062 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
1063 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
1064 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
1065 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
1067 if (pbx_builtin_serialize_variables(c, &out))
1068 ast_cli(a->fd," Variables:\n%s\n", out->str);
1069 if (c->cdr && ast_cdr_serialize_variables(c->cdr, &out, '=', '\n', 1))
1070 ast_cli(a->fd," CDR Variables:\n%s\n", out->str);
1072 ast_channel_unlock(c);
1077 * helper function to generate CLI matches from a fixed set of values.
1078 * A NULL word is acceptable.
1080 char *ast_cli_complete(const char *word, char *const choices[], int state)
1082 int i, which = 0, len;
1083 len = ast_strlen_zero(word) ? 0 : strlen(word);
1085 for (i = 0; choices[i]; i++) {
1086 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
1087 return ast_strdup(choices[i]);
1092 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
1094 struct ast_channel *c = NULL;
1097 char notfound = '\0';
1098 char *ret = ¬found; /* so NULL can break the loop */
1103 wordlen = strlen(word);
1105 while (ret == ¬found && (c = ast_channel_walk_locked(c))) {
1106 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
1107 ret = ast_strdup(c->name);
1108 ast_channel_unlock(c);
1110 return ret == ¬found ? NULL : ret;
1113 static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1115 #define FORMAT_STRING "%-25s %-20s %-20s\n"
1117 struct ast_group_info *gi = NULL;
1120 int havepattern = 0;
1124 e->command = "group show channels";
1126 "Usage: group show channels [pattern]\n"
1127 " Lists all currently active channels with channel group(s) specified.\n"
1128 " Optional regular expression pattern is matched to group names for each\n"
1135 if (a->argc < 3 || a->argc > 4)
1136 return CLI_SHOWUSAGE;
1139 if (regcomp(®exbuf, a->argv[3], REG_EXTENDED | REG_NOSUB))
1140 return CLI_SHOWUSAGE;
1144 ast_cli(a->fd, FORMAT_STRING, "Channel", "Group", "Category");
1146 ast_app_group_list_rdlock();
1148 gi = ast_app_group_list_head();
1150 if (!havepattern || !regexec(®exbuf, gi->group, 0, NULL, 0)) {
1151 ast_cli(a->fd, FORMAT_STRING, gi->chan->name, gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category));
1154 gi = AST_LIST_NEXT(gi, list);
1157 ast_app_group_list_unlock();
1162 ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
1164 #undef FORMAT_STRING
1167 static struct ast_cli_entry cli_debug_channel_deprecated = AST_CLI_DEFINE(handle_debugchan_deprecated, "Enable debugging on channel");
1168 static struct ast_cli_entry cli_module_load_deprecated = AST_CLI_DEFINE(handle_load_deprecated, "Load a module");
1169 static struct ast_cli_entry cli_module_reload_deprecated = AST_CLI_DEFINE(handle_reload_deprecated, "reload modules by name");
1170 static struct ast_cli_entry cli_module_unload_deprecated = AST_CLI_DEFINE(handle_unload_deprecated, "unload modules by name");
1172 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1174 static struct ast_cli_entry cli_cli[] = {
1175 /* Deprecated, but preferred command is now consolidated (and already has a deprecated command for it). */
1176 AST_CLI_DEFINE(handle_commandcomplete, "Command complete"),
1177 AST_CLI_DEFINE(handle_commandnummatches, "Returns number of command matches"),
1178 AST_CLI_DEFINE(handle_commandmatchesarray, "Returns command matches array"),
1180 AST_CLI_DEFINE(handle_nodebugchan_deprecated, "Disable debugging on channel(s)"),
1182 AST_CLI_DEFINE(handle_chanlist, "Display information on channels"),
1184 AST_CLI_DEFINE(handle_showcalls, "Display information on calls"),
1186 AST_CLI_DEFINE(handle_showchan, "Display information on a specific channel"),
1188 AST_CLI_DEFINE(handle_core_set_debug_channel, "Enable/disable debugging on a channel",
1189 .deprecate_cmd = &cli_debug_channel_deprecated),
1191 AST_CLI_DEFINE(handle_verbose, "Set level of debug/verbose chattiness"),
1193 AST_CLI_DEFINE(group_show_channels, "Display active channels with group(s)"),
1195 AST_CLI_DEFINE(handle_help, "Display help list, or specific help on a command"),
1197 AST_CLI_DEFINE(handle_logger_mute, "Toggle logging output to a console"),
1199 AST_CLI_DEFINE(handle_modlist, "List modules and info"),
1201 AST_CLI_DEFINE(handle_load, "Load a module by name", .deprecate_cmd = &cli_module_load_deprecated),
1203 AST_CLI_DEFINE(handle_reload, "Reload configuration", .deprecate_cmd = &cli_module_reload_deprecated),
1205 AST_CLI_DEFINE(handle_unload, "Unload a module by name", .deprecate_cmd = &cli_module_unload_deprecated ),
1207 AST_CLI_DEFINE(handle_showuptime, "Show uptime information"),
1209 AST_CLI_DEFINE(handle_softhangup, "Request a hangup on a given channel"),
1213 * Some regexp characters in cli arguments are reserved and used as separators.
1215 static const char cli_rsvd[] = "[]{}|*%";
1218 * initialize the _full_cmd string and related parameters,
1219 * return 0 on success, -1 on error.
1221 static int set_full_cmd(struct ast_cli_entry *e)
1226 ast_join(buf, sizeof(buf), e->cmda);
1227 e->_full_cmd = ast_strdup(buf);
1228 if (!e->_full_cmd) {
1229 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
1232 e->cmdlen = strcspn(e->_full_cmd, cli_rsvd);
1233 for (i = 0; e->cmda[i]; i++)
1239 /*! \brief initialize the _full_cmd string in * each of the builtins. */
1240 void ast_builtins_init(void)
1242 ast_cli_register_multiple(cli_cli, sizeof(cli_cli) / sizeof(struct ast_cli_entry));
1245 static struct ast_cli_entry *cli_next(struct ast_cli_entry *e)
1248 e = AST_LIST_FIRST(&helpers);
1250 e = AST_LIST_NEXT(e, list);
1255 * match a word in the CLI entry.
1256 * returns -1 on mismatch, 0 on match of an optional word,
1257 * 1 on match of a full word.
1259 * The pattern can be
1260 * any_word match for equal
1261 * [foo|bar|baz] optionally, one of these words
1262 * {foo|bar|baz} exactly, one of these words
1265 static int word_match(const char *cmd, const char *cli_word)
1270 if (ast_strlen_zero(cmd) || ast_strlen_zero(cli_word))
1272 if (!strchr(cli_rsvd, cli_word[0])) /* normal match */
1273 return (strcasecmp(cmd, cli_word) == 0) ? 1 : -1;
1274 /* regexp match, takes [foo|bar] or {foo|bar} */
1276 /* wildcard match - will extend in the future */
1277 if (l > 0 && cli_word[0] == '%') {
1278 return 1; /* wildcard */
1280 pos = strcasestr(cli_word, cmd);
1281 if (pos == NULL) /* not found, say ok if optional */
1282 return cli_word[0] == '[' ? 0 : -1;
1283 if (pos == cli_word) /* no valid match at the beginning */
1285 if (strchr(cli_rsvd, pos[-1]) && strchr(cli_rsvd, pos[l]))
1286 return 1; /* valid match */
1287 return -1; /* not found */
1290 /*! \brief if word is a valid prefix for token, returns the pos-th
1291 * match as a malloced string, or NULL otherwise.
1292 * Always tell in *actual how many matches we got.
1294 static char *is_prefix(const char *word, const char *token,
1295 int pos, int *actual)
1301 if (ast_strlen_zero(token))
1303 if (ast_strlen_zero(word))
1304 word = ""; /* dummy */
1306 if (strcspn(word, cli_rsvd) != lw)
1307 return NULL; /* no match if word has reserved chars */
1308 if (strchr(cli_rsvd, token[0]) == NULL) { /* regular match */
1309 if (strncasecmp(token, word, lw)) /* no match */
1312 return (pos != 0) ? NULL : ast_strdup(token);
1314 /* now handle regexp match */
1316 /* Wildcard always matches, so we never do is_prefix on them */
1318 t1 = ast_strdupa(token + 1); /* copy, skipping first char */
1319 while (pos >= 0 && (s = strsep(&t1, cli_rsvd)) && *s) {
1320 if (*s == '%') /* wildcard */
1322 if (strncasecmp(s, word, lw)) /* no match */
1326 return ast_strdup(s);
1332 * \brief locate a cli command in the 'helpers' list (which must be locked).
1333 * exact has 3 values:
1334 * 0 returns if the search key is equal or longer than the entry.
1335 * note that trailing optional arguments are skipped.
1336 * -1 true if the mismatch is on the last word XXX not true!
1337 * 1 true only on complete, exact match.
1339 * The search compares word by word taking care of regexps in e->cmda
1341 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1343 int matchlen = -1; /* length of longest match so far */
1344 struct ast_cli_entry *cand = NULL, *e=NULL;
1346 while ( (e = cli_next(e)) ) {
1347 /* word-by word regexp comparison */
1348 char * const *src = cmds;
1349 char * const *dst = e->cmda;
1351 for (;; dst++, src += n) {
1352 n = word_match(*src, *dst);
1356 if (ast_strlen_zero(*dst) || ((*dst)[0] == '[' && ast_strlen_zero(dst[1]))) {
1357 /* no more words in 'e' */
1358 if (ast_strlen_zero(*src)) /* exact match, cannot do better */
1360 /* Here, cmds has more words than the entry 'e' */
1361 if (match_type != 0) /* but we look for almost exact match... */
1362 continue; /* so we skip this one. */
1363 /* otherwise we like it (case 0) */
1364 } else { /* still words in 'e' */
1365 if (ast_strlen_zero(*src))
1366 continue; /* cmds is shorter than 'e', not good */
1367 /* Here we have leftover words in cmds and 'e',
1368 * but there is a mismatch. We only accept this one if match_type == -1
1369 * and this is the last word for both.
1371 if (match_type != -1 || !ast_strlen_zero(src[1]) ||
1372 !ast_strlen_zero(dst[1])) /* not the one we look for */
1374 /* good, we are in case match_type == -1 and mismatch on last word */
1376 if (src - cmds > matchlen) { /* remember the candidate */
1377 matchlen = src - cmds;
1381 return e ? e : cand;
1384 static char *find_best(char *argv[])
1386 static char cmdline[80];
1388 /* See how close we get, then print the candidate */
1389 char *myargv[AST_MAX_CMD_LEN];
1390 for (x=0;x<AST_MAX_CMD_LEN;x++)
1392 AST_RWLIST_RDLOCK(&helpers);
1393 for (x=0;argv[x];x++) {
1394 myargv[x] = argv[x];
1395 if (!find_cli(myargv, -1))
1398 AST_RWLIST_UNLOCK(&helpers);
1399 ast_join(cmdline, sizeof(cmdline), myargv);
1403 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1405 if (e->deprecate_cmd) {
1406 __ast_cli_unregister(e->deprecate_cmd, e);
1409 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1411 AST_RWLIST_WRLOCK(&helpers);
1412 AST_RWLIST_REMOVE(&helpers, e, list);
1413 AST_RWLIST_UNLOCK(&helpers);
1414 ast_free(e->_full_cmd);
1415 e->_full_cmd = NULL;
1417 /* this is a new-style entry. Reset fields and free memory. */
1418 bzero((char **)(e->cmda), sizeof(e->cmda));
1419 ast_free(e->command);
1427 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1429 struct ast_cli_entry *cur;
1430 int i, lf, ret = -1;
1432 struct ast_cli_args a; /* fake argument */
1433 char **dst = (char **)e->cmda; /* need to cast as the entry is readonly */
1436 bzero (&a, sizeof(a));
1437 e->handler(e, CLI_INIT, &a);
1438 /* XXX check that usage and command are filled up */
1439 s = ast_skip_blanks(e->command);
1440 s = e->command = ast_strdup(s);
1441 for (i=0; !ast_strlen_zero(s) && i < AST_MAX_CMD_LEN-1; i++) {
1442 *dst++ = s; /* store string */
1443 s = ast_skip_nonblanks(s);
1444 if (*s == '\0') /* we are done */
1447 s = ast_skip_blanks(s);
1451 AST_RWLIST_WRLOCK(&helpers);
1453 if (find_cli(e->cmda, 1)) {
1454 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", e->_full_cmd);
1457 if (set_full_cmd(e))
1463 e->summary = ed->summary;
1464 e->usage = ed->usage;
1465 /* XXX If command A deprecates command B, and command B deprecates command C...
1466 Do we want to show command A or command B when telling the user to use new syntax?
1467 This currently would show command A.
1468 To show command B, you just need to always use ed->_full_cmd.
1470 e->_deprecated_by = S_OR(ed->_deprecated_by, ed->_full_cmd);
1474 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1475 int len = cur->cmdlen;
1478 if (strncasecmp(e->_full_cmd, cur->_full_cmd, len) < 0) {
1479 AST_RWLIST_INSERT_BEFORE_CURRENT(e, list);
1483 AST_RWLIST_TRAVERSE_SAFE_END;
1486 AST_RWLIST_INSERT_TAIL(&helpers, e, list);
1487 ret = 0; /* success */
1490 AST_RWLIST_UNLOCK(&helpers);
1492 if (e->deprecate_cmd) {
1493 /* This command deprecates another command. Register that one also. */
1494 __ast_cli_register(e->deprecate_cmd, e);
1500 /* wrapper function, so we can unregister deprecated commands recursively */
1501 int ast_cli_unregister(struct ast_cli_entry *e)
1503 return __ast_cli_unregister(e, NULL);
1506 /* wrapper function, so we can register deprecated commands recursively */
1507 int ast_cli_register(struct ast_cli_entry *e)
1509 return __ast_cli_register(e, NULL);
1513 * register/unregister an array of entries.
1515 int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1519 for (i = 0; i < len; i++)
1520 res |= ast_cli_register(e + i);
1525 int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1529 for (i = 0; i < len; i++)
1530 res |= ast_cli_unregister(e + i);
1536 /*! \brief helper for final part of
1537 * handle_help. if locked = 0 it's just "help_workhorse",
1538 * otherwise assume the list is already locked and print
1539 * an error message if not found.
1541 static char *help1(int fd, char *match[], int locked)
1543 char matchstr[80] = "";
1544 struct ast_cli_entry *e = NULL;
1549 ast_join(matchstr, sizeof(matchstr), match);
1550 len = strlen(matchstr);
1553 AST_RWLIST_RDLOCK(&helpers);
1554 while ( (e = cli_next(e)) ) {
1555 /* Hide commands that start with '_' */
1556 if (e->_full_cmd[0] == '_')
1558 /* Hide commands that are marked as deprecated. */
1561 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1563 ast_cli(fd, "%30.30s %s\n", e->_full_cmd, S_OR(e->summary, "<no description available>"));
1567 AST_RWLIST_UNLOCK(&helpers);
1568 if (!locked && !found && matchstr[0])
1569 ast_cli(fd, "No such command '%s'.\n", matchstr);
1573 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1576 struct ast_cli_entry *my_e;
1578 if (cmd == CLI_INIT) {
1579 e->command = "help";
1581 "Usage: help [topic]\n"
1582 " When called with a topic as an argument, displays usage\n"
1583 " information on the given command. If called without a\n"
1584 " topic, it provides a list of commands.\n";
1587 } else if (cmd == CLI_GENERATE) {
1588 /* skip first 4 or 5 chars, "help " */
1589 int l = strlen(a->line);
1593 /* XXX watch out, should stop to the non-generator parts */
1594 return __ast_cli_generator(a->line + l, a->word, a->n, 0);
1597 return help1(a->fd, NULL, 0);
1599 AST_RWLIST_RDLOCK(&helpers);
1600 my_e = find_cli(a->argv + 1, 1); /* try exact match first */
1602 return help1(a->fd, a->argv + 1, 1 /* locked */);
1604 ast_cli(a->fd, "%s", my_e->usage);
1606 ast_join(fullcmd, sizeof(fullcmd), a->argv+1);
1607 ast_cli(a->fd, "No help text available for '%s'.\n", fullcmd);
1609 AST_RWLIST_UNLOCK(&helpers);
1613 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1622 if (trailingwhitespace == NULL)
1623 trailingwhitespace = &dummy;
1624 *trailingwhitespace = 0;
1625 if (s == NULL) /* invalid, though! */
1627 /* make a copy to store the parsed string */
1628 if (!(dup = ast_strdup(s)))
1632 /* scan the original string copying into cur when needed */
1635 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1638 if (*s == '"' && !escaped) {
1640 if (quoted && whitespace) {
1641 /* start a quoted string from previous whitespace: new argument */
1645 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1646 /* If we are not already in whitespace, and not in a quoted string or
1647 processing an escape sequence, and just entered whitespace, then
1648 finalize the previous argument and remember that we are in whitespace
1654 } else if (*s == '\\' && !escaped) {
1658 /* we leave whitespace, and are not quoted. So it's a new argument */
1666 /* Null terminate */
1668 /* XXX put a NULL in the last argument, because some functions that take
1669 * the array may want a null-terminated array.
1670 * argc still reflects the number of non-NULL entries.
1674 *trailingwhitespace = whitespace;
1678 /*! \brief Return the number of unique matches for the generator */
1679 int ast_cli_generatornummatches(const char *text, const char *word)
1681 int matches = 0, i = 0;
1682 char *buf = NULL, *oldbuf = NULL;
1684 while ((buf = ast_cli_generator(text, word, i++))) {
1685 if (!oldbuf || strcmp(buf,oldbuf))
1696 char **ast_cli_completion_matches(const char *text, const char *word)
1698 char **match_list = NULL, *retstr, *prevstr;
1699 size_t match_list_len, max_equal, which, i;
1702 /* leave entry 0 free for the longest common substring */
1704 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1705 if (matches + 1 >= match_list_len) {
1706 match_list_len <<= 1;
1707 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1710 match_list[++matches] = retstr;
1714 return match_list; /* NULL */
1716 /* Find the longest substring that is common to all results
1717 * (it is a candidate for completion), and store a copy in entry 0.
1719 prevstr = match_list[1];
1720 max_equal = strlen(prevstr);
1721 for (which = 2; which <= matches; which++) {
1722 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1727 if (!(retstr = ast_malloc(max_equal + 1)))
1730 ast_copy_string(retstr, match_list[1], max_equal + 1);
1731 match_list[0] = retstr;
1733 /* ensure that the array is NULL terminated */
1734 if (matches + 1 >= match_list_len) {
1735 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1738 match_list[matches + 1] = NULL;
1743 /*! \brief returns true if there are more words to match */
1744 static int more_words (char * const *dst)
1747 for (i = 0; dst[i]; i++) {
1748 if (dst[i][0] != '[')
1755 * generate the entry at position 'state'
1757 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1759 char *argv[AST_MAX_ARGS];
1760 struct ast_cli_entry *e = NULL;
1761 int x = 0, argindex, matchlen;
1764 char matchstr[80] = "";
1766 /* Split the argument into an array of words */
1767 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1769 if (!dup) /* malloc error */
1772 /* Compute the index of the last argument (could be an empty string) */
1773 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1775 /* rebuild the command, ignore terminating white space and flatten space */
1776 ast_join(matchstr, sizeof(matchstr)-1, argv);
1777 matchlen = strlen(matchstr);
1779 strcat(matchstr, " "); /* XXX */
1784 AST_RWLIST_RDLOCK(&helpers);
1785 while ( (e = cli_next(e)) ) {
1786 /* XXX repeated code */
1787 int src = 0, dst = 0, n = 0;
1789 if (e->command[0] == '_')
1793 * Try to match words, up to and excluding the last word, which
1794 * is either a blank or something that we want to extend.
1796 for (;src < argindex; dst++, src += n) {
1797 n = word_match(argv[src], e->cmda[dst]);
1802 if (src != argindex && more_words(e->cmda + dst)) /* not a match */
1804 ret = is_prefix(argv[src], e->cmda[dst], state - matchnum, &n);
1805 matchnum += n; /* this many matches here */
1808 * argv[src] is a valid prefix of the next word in this
1809 * command. If this is also the correct entry, return it.
1811 if (matchnum > state)
1815 } else if (ast_strlen_zero(e->cmda[dst])) {
1817 * This entry is a prefix of the command string entered
1818 * (only one entry in the list should have this property).
1819 * Run the generator if one is available. In any case we are done.
1821 if (e->handler) { /* new style command */
1822 struct ast_cli_args a = {
1823 .line = matchstr, .word = word,
1825 .n = state - matchnum };
1826 ret = e->handler(e, CLI_GENERATE, &a);
1833 AST_RWLIST_UNLOCK(&helpers);
1838 char *ast_cli_generator(const char *text, const char *word, int state)
1840 return __ast_cli_generator(text, word, state, 1);
1843 int ast_cli_command(int fd, const char *s)
1845 char *args[AST_MAX_ARGS + 1];
1846 struct ast_cli_entry *e;
1848 char *dup = parse_args(s, &x, args + 1, AST_MAX_ARGS, NULL);
1849 char *retval = NULL;
1850 struct ast_cli_args a = {
1851 .fd = fd, .argc = x, .argv = args+1 };
1856 if (x < 1) /* We need at least one entry, otherwise ignore */
1859 AST_RWLIST_RDLOCK(&helpers);
1860 e = find_cli(args + 1, 0);
1862 ast_atomic_fetchadd_int(&e->inuse, 1);
1863 AST_RWLIST_UNLOCK(&helpers);
1865 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(args + 1));
1869 * Within the handler, argv[-1] contains a pointer to the ast_cli_entry.
1870 * Remember that the array returned by parse_args is NULL-terminated.
1872 args[0] = (char *)e;
1874 retval = e->handler(e, CLI_HANDLER, &a);
1876 if (retval == CLI_SHOWUSAGE) {
1877 ast_cli(fd, "%s", S_OR(e->usage, "Invalid usage, but no usage information available.\n"));
1878 AST_RWLIST_RDLOCK(&helpers);
1880 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);
1881 AST_RWLIST_UNLOCK(&helpers);
1883 if (retval == CLI_FAILURE)
1884 ast_cli(fd, "Command '%s' failed.\n", s);
1885 AST_RWLIST_RDLOCK(&helpers);
1886 if (e->deprecated == 1) {
1887 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);
1890 AST_RWLIST_UNLOCK(&helpers);
1892 ast_atomic_fetchadd_int(&e->inuse, -1);
1898 int ast_cli_command_multiple(int fd, size_t size, const char *s)
1901 int x, y = 0, count = 0;
1903 for (x = 0; x < size; x++) {
1907 ast_cli_command(fd, cmd);