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$")
32 #include <sys/signal.h>
39 #include "asterisk/logger.h"
40 #include "asterisk/options.h"
41 #include "asterisk/cli.h"
42 #include "asterisk/linkedlists.h"
43 #include "asterisk/module.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/app.h"
48 #include "asterisk/lock.h"
49 #include "editline/readline/readline.h"
50 #include "asterisk/threadstorage.h"
52 AST_THREADSTORAGE(ast_cli_buf);
54 /*! \brief Initial buffer size for resulting strings in ast_cli() */
55 #define AST_CLI_INITLEN 256
57 void ast_cli(int fd, const char *fmt, ...)
63 if (!(buf = ast_str_thread_get(&ast_cli_buf, AST_CLI_INITLEN)))
67 res = ast_str_set_va(&buf, 0, fmt, ap);
70 if (res != AST_DYNSTR_BUILD_FAILED)
71 ast_carefulwrite(fd, buf->str, strlen(buf->str), 100);
74 static AST_LIST_HEAD_STATIC(helpers, ast_cli_entry);
76 static const char logger_mute_help[] =
77 "Usage: logger mute\n"
78 " Disables logging output to the current console, making it possible to\n"
79 " gather information without being disturbed by scrolling lines.\n";
81 static const char softhangup_help[] =
82 "Usage: soft hangup <channel>\n"
83 " Request that a channel be hung up. The hangup takes effect\n"
84 " the next time the driver reads or writes from the channel\n";
86 static const char group_show_channels_help[] =
87 "Usage: group show channels [pattern]\n"
88 " Lists all currently active channels with channel group(s) specified.\n"
89 " Optional regular expression pattern is matched to group names for each\n"
92 static char *complete_fn(const char *word, int state)
98 ast_copy_string(filename, word, sizeof(filename));
100 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
102 /* XXX the following function is not reentrant, so we better not use it */
103 c = filename_completion_function(filename, state);
105 if (c && word[0] != '/')
106 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
108 return c ? ast_strdup(c) : c;
111 static char *handle_load(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
113 /* "module load <mod>" */
116 e->command = "module load";
118 "Usage: module load <module name>\n"
119 " Loads the specified module into Asterisk.\n";
123 if (a->pos != e->args)
125 return complete_fn(a->word, a->n);
127 if (a->argc != e->args + 1)
128 return CLI_SHOWUSAGE;
129 if (ast_load_resource(a->argv[e->args])) {
130 ast_cli(a->fd, "Unable to load module %s\n", a->argv[e->args]);
136 static char *handle_load_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
138 char *res = handle_load(e, cmd, a);
144 static char *handle_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
150 e->command = "module reload";
152 "Usage: module reload [module ...]\n"
153 " Reloads configuration files for all listed modules which support\n"
154 " reloading, or for all supported modules if none are listed.\n";
158 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 1);
160 if (a->argc == e->args) {
161 ast_module_reload(NULL);
164 for (x = e->args; x < a->argc; x++) {
165 int res = ast_module_reload(a->argv[x]);
166 /* XXX reload has multiple error returns, including -1 on error and 2 on success */
169 ast_cli(a->fd, "No such module '%s'\n", a->argv[x]);
172 ast_cli(a->fd, "Module '%s' does not support reload\n", a->argv[x]);
179 static char *handle_reload_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
181 char *s = handle_reload(e, cmd, a);
182 if (cmd == CLI_INIT) /* override command name */
183 e->command = "reload";
187 static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
194 char **argv = a->argv;
200 e->command = "core set {debug|verbose} [off|atleast]";
202 "Usage: core set {debug|verbose} [atleast] <level>\n"
203 " core set {debug|verbose} off\n"
204 " Sets level of debug or verbose messages to be displayed.\n"
205 " 0 or off means no messages should be displayed.\n"
206 " Equivalent to -d[d[...]] or -v[v[v...]] on startup\n";
212 /* all the above return, so we proceed with the handler.
213 * we are guaranteed to be called with argc >= e->args;
217 return CLI_SHOWUSAGE;
218 if (!strcasecmp(argv[e->args - 2], "debug")) {
220 oldval = option_debug;
223 dst = &option_verbose;
224 oldval = option_verbose;
227 if (argc == e->args && !strcasecmp(argv[e->args - 1], "off")) {
231 if (!strcasecmp(argv[e->args-1], "atleast"))
233 if (argc != e->args + atleast)
234 return CLI_SHOWUSAGE;
235 if (sscanf(argv[e->args + atleast - 1], "%d", &newlevel) != 1)
236 return CLI_SHOWUSAGE;
239 if (!atleast || newlevel > *dst)
241 if (oldval > 0 && *dst == 0)
242 ast_cli(fd, "%s is now OFF\n", what);
245 ast_cli(fd, "%s is at least %d\n", what, *dst);
247 ast_cli(fd, "%s was %d and is now %d\n", what, oldval, *dst);
253 static int handle_logger_mute(int fd, int argc, char *argv[])
256 return RESULT_SHOWUSAGE;
257 ast_console_toggle_mute(fd);
258 return RESULT_SUCCESS;
261 static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
263 /* "module unload mod_1 [mod_2 .. mod_N]" */
265 int force = AST_FORCE_SOFT;
270 e->command = "module unload";
272 "Usage: module unload [-f|-h] <module_1> [<module_2> ... ]\n"
273 " Unloads the specified module from Asterisk. The -f\n"
274 " option causes the module to be unloaded even if it is\n"
275 " in use (may cause a crash) and the -h module causes the\n"
276 " module to be unloaded even if the module says it cannot, \n"
277 " which almost always will cause a crash.\n";
281 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
283 if (a->argc < e->args + 1)
284 return CLI_SHOWUSAGE;
285 x = e->args; /* first argument */
289 force = AST_FORCE_FIRM;
290 else if (s[1] == 'h')
291 force = AST_FORCE_HARD;
293 return CLI_SHOWUSAGE;
294 if (a->argc < e->args + 2) /* need at least one module name */
295 return CLI_SHOWUSAGE;
296 x++; /* skip this argument */
299 for (; x < a->argc; x++) {
300 if (ast_unload_resource(a->argv[x], force)) {
301 ast_cli(a->fd, "Unable to unload resource %s\n", a->argv[x]);
308 static char *handle_unload_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
310 char *res = handle_unload(e, cmd, a);
312 e->command = "unload"; /* XXX override */
316 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
317 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
319 AST_MUTEX_DEFINE_STATIC(climodentrylock);
320 static int climodentryfd = -1;
322 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
324 /* Comparing the like with the module */
325 if (strcasestr(module, like) ) {
326 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
332 static void print_uptimestr(int fd, struct timeval timeval, const char *prefix, int printsec)
334 int x; /* the main part - years, weeks, etc. */
338 #define MINUTE (SECOND*60)
339 #define HOUR (MINUTE*60)
340 #define DAY (HOUR*24)
342 #define YEAR (DAY*365)
343 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
344 if (timeval.tv_sec < 0) /* invalid, nothing to show */
347 if (printsec) { /* plain seconds output */
348 ast_cli(fd, "%s: %lu\n", prefix, (u_long)timeval.tv_sec);
351 out = ast_str_alloca(256);
352 if (timeval.tv_sec > YEAR) {
353 x = (timeval.tv_sec / YEAR);
354 timeval.tv_sec -= (x * YEAR);
355 ast_str_append(&out, 0, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
357 if (timeval.tv_sec > WEEK) {
358 x = (timeval.tv_sec / WEEK);
359 timeval.tv_sec -= (x * WEEK);
360 ast_str_append(&out, 0, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
362 if (timeval.tv_sec > DAY) {
363 x = (timeval.tv_sec / DAY);
364 timeval.tv_sec -= (x * DAY);
365 ast_str_append(&out, 0, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
367 if (timeval.tv_sec > HOUR) {
368 x = (timeval.tv_sec / HOUR);
369 timeval.tv_sec -= (x * HOUR);
370 ast_str_append(&out, 0, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
372 if (timeval.tv_sec > MINUTE) {
373 x = (timeval.tv_sec / MINUTE);
374 timeval.tv_sec -= (x * MINUTE);
375 ast_str_append(&out, 0, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
378 if (x > 0 || out->used == 0) /* if there is nothing, print 0 seconds */
379 ast_str_append(&out, 0, "%d second%s ", x, ESS(x));
380 ast_cli(fd, "%s: %s\n", prefix, out->str);
383 static char * handle_showuptime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
385 struct timeval curtime = ast_tvnow();
390 e->command = "core show uptime [seconds]";
392 "Usage: core show uptime [seconds]\n"
393 " Shows Asterisk uptime information.\n"
394 " The seconds word returns the uptime in seconds only.\n";
400 /* regular handler */
401 if (a->argc == e->args && !strcasecmp(a->argv[e->args-1],"seconds"))
403 else if (a->argc == e->args-1)
406 return CLI_SHOWUSAGE;
407 if (ast_startuptime.tv_sec)
408 print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
409 if (ast_lastreloadtime.tv_sec)
410 print_uptimestr(a->fd, ast_tvsub(curtime, ast_lastreloadtime), "Last reload", printsec);
414 static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
420 e->command = "module show [like]";
422 "Usage: module show [like keyword]\n"
423 " Shows Asterisk modules currently in use, and usage statistics.\n";
427 if (a->pos == e->args)
428 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
432 /* all the above return, so we proceed with the handler.
433 * we are guaranteed to have argc >= e->args
435 if (a->argc == e->args - 1)
437 else if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args-1], "like") )
438 like = a->argv[e->args];
440 return CLI_SHOWUSAGE;
442 ast_mutex_lock(&climodentrylock);
443 climodentryfd = a->fd; /* global, protected by climodentrylock */
444 ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
445 ast_cli(a->fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
447 ast_mutex_unlock(&climodentrylock);
448 return RESULT_SUCCESS;
450 #undef MODLIST_FORMAT
451 #undef MODLIST_FORMAT2
453 static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
455 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
456 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
457 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s\n"
458 #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"
459 #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"
461 struct ast_channel *c = NULL;
462 int numchans = 0, concise = 0, verbose = 0, count = 0;
468 e->command = "core show channels [concise|verbose|count]";
470 "Usage: core show channels [concise|verbose|count]\n"
471 " Lists currently defined channels and some information about them. If\n"
472 " 'concise' is specified, the format is abridged and in a more easily\n"
473 " machine parsable format. If 'verbose' is specified, the output includes\n"
474 " more and longer fields. If 'count' is specified only the channel and call\n"
475 " count is output.\n";
485 if (a->argc == e->args) {
486 if (!strcasecmp(argv[e->args-1],"concise"))
488 else if (!strcasecmp(argv[e->args-1],"verbose"))
490 else if (!strcasecmp(argv[e->args-1],"count"))
493 return CLI_SHOWUSAGE;
494 } else if (a->argc != e->args - 1)
495 return CLI_SHOWUSAGE;
498 if (!concise && !verbose)
499 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
501 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
502 "CallerID", "Duration", "Accountcode", "BridgedTo");
505 while ((c = ast_channel_walk_locked(c)) != NULL) {
506 struct ast_channel *bc = ast_bridged_channel(c);
507 char durbuf[10] = "-";
510 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
511 int duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
513 int durh = duration / 3600;
514 int durm = (duration % 3600) / 60;
515 int durs = duration % 60;
516 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
518 snprintf(durbuf, sizeof(durbuf), "%d", duration);
522 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
523 c->appl ? c->appl : "(None)",
524 S_OR(c->data, ""), /* XXX different from verbose ? */
525 S_OR(c->cid.cid_num, ""),
526 S_OR(c->accountcode, ""),
529 bc ? bc->name : "(None)");
530 } else if (verbose) {
531 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
532 c->appl ? c->appl : "(None)",
533 c->data ? S_OR(c->data, "(Empty)" ): "(None)",
534 S_OR(c->cid.cid_num, ""),
536 S_OR(c->accountcode, ""),
537 bc ? bc->name : "(None)");
539 char locbuf[40] = "(None)";
540 char appdata[40] = "(None)";
542 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
543 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
545 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, S_OR(c->data, ""));
546 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
550 ast_channel_unlock(c);
553 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
555 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
556 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
557 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
559 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
564 #undef FORMAT_STRING2
565 #undef CONCISE_FORMAT_STRING
566 #undef VERBOSE_FORMAT_STRING
567 #undef VERBOSE_FORMAT_STRING2
570 static const char showchan_help[] =
571 "Usage: core show channel <channel>\n"
572 " Shows lots of information about the specified channel.\n";
574 static const char commandcomplete_help[] =
575 "Usage: _command complete \"<line>\" text state\n"
576 " This function is used internally to help with command completion and should.\n"
577 " never be called by the user directly.\n";
579 static const char commandnummatches_help[] =
580 "Usage: _command nummatches \"<line>\" text \n"
581 " This function is used internally to help with command completion and should.\n"
582 " never be called by the user directly.\n";
584 static const char commandmatchesarray_help[] =
585 "Usage: _command matchesarray \"<line>\" text \n"
586 " This function is used internally to help with command completion and should.\n"
587 " never be called by the user directly.\n";
589 static int handle_softhangup(int fd, int argc, char *argv[])
591 struct ast_channel *c=NULL;
593 return RESULT_SHOWUSAGE;
594 c = ast_get_channel_by_name_locked(argv[2]);
596 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
597 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
598 ast_channel_unlock(c);
600 ast_cli(fd, "%s is not a known channel\n", argv[2]);
601 return RESULT_SUCCESS;
604 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
606 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
615 return RESULT_SHOWUSAGE;
616 if (!(buf = ast_malloc(buflen)))
617 return RESULT_FAILURE;
619 matches = ast_cli_completion_matches(argv[2], argv[3]);
621 for (x=0; matches[x]; x++) {
622 matchlen = strlen(matches[x]) + 1;
623 if (len + matchlen >= buflen) {
624 buflen += matchlen * 3;
626 if (!(buf = ast_realloc(obuf, buflen)))
627 /* Memory allocation failure... Just free old buffer and be done */
631 len += sprintf( buf + len, "%s ", matches[x]);
632 ast_free(matches[x]);
639 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
642 ast_cli(fd, "NULL\n");
644 return RESULT_SUCCESS;
649 static int handle_commandnummatches(int fd, int argc, char *argv[])
654 return RESULT_SHOWUSAGE;
656 matches = ast_cli_generatornummatches(argv[2], argv[3]);
658 ast_cli(fd, "%d", matches);
660 return RESULT_SUCCESS;
663 static int handle_commandcomplete(int fd, int argc, char *argv[])
668 return RESULT_SHOWUSAGE;
669 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
674 ast_cli(fd, "NULL\n");
675 return RESULT_SUCCESS;
678 static char *handle_core_set_debug_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
680 struct ast_channel *c = NULL;
681 int is_all, is_off = 0;
685 e->command = "core set debug channel";
687 "Usage: core set debug channel <all|channel> [off]\n"
688 " Enables/disables debugging on all or on a specific channel.\n";
692 /* XXX remember to handle the optional "off" */
693 if (a->pos != e->args)
695 return a->n == 0 ? ast_strdup("all") : ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
697 /* 'core set debug channel {all|chan_id}' */
698 if (a->argc == e->args + 2) {
699 if (!strcasecmp(a->argv[e->args + 1], "off"))
702 return CLI_SHOWUSAGE;
703 } else if (a->argc != e->args + 1)
704 return CLI_SHOWUSAGE;
706 is_all = !strcasecmp("all", a->argv[e->args]);
709 global_fin &= ~DEBUGCHAN_FLAG;
710 global_fout &= ~DEBUGCHAN_FLAG;
712 global_fin |= DEBUGCHAN_FLAG;
713 global_fout |= DEBUGCHAN_FLAG;
715 c = ast_channel_walk_locked(NULL);
717 c = ast_get_channel_by_name_locked(a->argv[e->args]);
719 ast_cli(a->fd, "No such channel %s\n", a->argv[e->args]);
722 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
724 c->fin &= ~DEBUGCHAN_FLAG;
725 c->fout &= ~DEBUGCHAN_FLAG;
727 c->fin |= DEBUGCHAN_FLAG;
728 c->fout |= DEBUGCHAN_FLAG;
730 ast_cli(a->fd, "Debugging %s on channel %s\n", is_off ? "disabled" : "enabled", c->name);
732 ast_channel_unlock(c);
735 c = ast_channel_walk_locked(c);
737 ast_cli(a->fd, "Debugging on new channels is %s\n", is_off ? "disabled" : "enabled");
738 return RESULT_SUCCESS;
741 static char *handle_debugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
745 if (cmd == CLI_HANDLER && a->argc != e->args + 1)
746 return CLI_SHOWUSAGE;
747 res = handle_core_set_debug_channel(e, cmd, a);
749 e->command = "debug channel";
753 static char *handle_nodebugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
756 if (cmd == CLI_HANDLER) {
757 if (a->argc != e->args + 1)
758 return CLI_SHOWUSAGE;
759 /* pretend we have an extra "off" at the end. We can do this as the array
760 * is NULL terminated so we overwrite that entry.
762 a->argv[e->args+1] = "off";
765 res = handle_core_set_debug_channel(e, cmd, a);
767 e->command = "no debug channel";
771 static int handle_showchan(int fd, int argc, char *argv[])
773 struct ast_channel *c=NULL;
775 struct ast_str *out = ast_str_alloca(2048);
777 char nf[256], wf[256], rf[256];
778 long elapsed_seconds=0;
779 int hour=0, min=0, sec=0;
782 return RESULT_SHOWUSAGE;
784 c = ast_get_channel_by_name_locked(argv[3]);
786 ast_cli(fd, "%s is not a known channel\n", argv[3]);
787 return RESULT_SUCCESS;
790 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
791 hour = elapsed_seconds / 3600;
792 min = (elapsed_seconds % 3600) / 60;
793 sec = elapsed_seconds % 60;
794 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
796 strcpy(cdrtime, "N/A");
803 " Caller ID Name: %s\n"
808 " NativeFormats: %s\n"
811 " WriteTranscode: %s\n"
812 " ReadTranscode: %s\n"
813 "1st File Descriptor: %d\n"
815 " Frames out: %d%s\n"
816 " Time to Hangup: %ld\n"
817 " Elapsed Time: %s\n"
818 " Direct Bridge: %s\n"
819 "Indirect Bridge: %s\n"
824 " Call Group: %llu\n"
825 " Pickup Group: %llu\n"
828 " Blocking in: %s\n",
829 c->name, c->tech->type, c->uniqueid,
830 S_OR(c->cid.cid_num, "(N/A)"),
831 S_OR(c->cid.cid_name, "(N/A)"),
832 S_OR(c->cid.cid_dnid, "(N/A)"),
834 ast_state2str(c->_state), c->_state, c->rings,
835 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
836 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
837 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
838 c->writetrans ? "Yes" : "No",
839 c->readtrans ? "Yes" : "No",
841 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
842 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
843 (long)c->whentohangup,
844 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
845 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
846 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
847 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
849 if (pbx_builtin_serialize_variables(c, &out))
850 ast_cli(fd," Variables:\n%s\n", out->str);
851 if (c->cdr && ast_cdr_serialize_variables(c->cdr, &out, '=', '\n', 1))
852 ast_cli(fd," CDR Variables:\n%s\n", out->str);
854 ast_channel_unlock(c);
855 return RESULT_SUCCESS;
859 * helper function to generate CLI matches from a fixed set of values.
860 * A NULL word is acceptable.
862 char *ast_cli_complete(const char *word, char *const choices[], int state)
864 int i, which = 0, len;
865 len = ast_strlen_zero(word) ? 0 : strlen(word);
867 for (i = 0; choices[i]; i++) {
868 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
869 return ast_strdup(choices[i]);
874 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
876 struct ast_channel *c = NULL;
879 char notfound = '\0';
880 char *ret = ¬found; /* so NULL can break the loop */
885 wordlen = strlen(word);
887 while (ret == ¬found && (c = ast_channel_walk_locked(c))) {
888 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
889 ret = ast_strdup(c->name);
890 ast_channel_unlock(c);
892 return ret == ¬found ? NULL : ret;
895 static char *complete_ch_3(const char *line, const char *word, int pos, int state)
897 return ast_complete_channels(line, word, pos, state, 2);
900 static char *complete_ch_4(const char *line, const char *word, int pos, int state)
902 return ast_complete_channels(line, word, pos, state, 3);
905 static int group_show_channels(int fd, int argc, char *argv[])
907 #define FORMAT_STRING "%-25s %-20s %-20s\n"
909 struct ast_group_info *gi = NULL;
914 if (argc < 3 || argc > 4)
915 return RESULT_SHOWUSAGE;
918 if (regcomp(®exbuf, argv[3], REG_EXTENDED | REG_NOSUB))
919 return RESULT_SHOWUSAGE;
923 ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
925 ast_app_group_list_rdlock();
927 gi = ast_app_group_list_head();
929 if (!havepattern || !regexec(®exbuf, gi->group, 0, NULL, 0)) {
930 ast_cli(fd, FORMAT_STRING, gi->chan->name, gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category));
933 gi = AST_LIST_NEXT(gi, list);
936 ast_app_group_list_unlock();
941 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
942 return RESULT_SUCCESS;
946 /* XXX Nothing in this array can currently be deprecated...
947 You have to change the way find_cli works in order to remove this array
948 I recommend doing this eventually...
950 static struct ast_cli_entry builtins[] = {
951 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
952 { { "_command", "complete", NULL },
953 handle_commandcomplete, "Command complete",
954 commandcomplete_help },
956 { { "_command", "nummatches", NULL },
957 handle_commandnummatches, "Returns number of command matches",
958 commandnummatches_help },
960 { { "_command", "matchesarray", NULL },
961 handle_commandmatchesarray, "Returns command matches array",
962 commandmatchesarray_help },
964 { { NULL }, NULL, NULL, NULL }
967 static struct ast_cli_entry cli_debug_channel_deprecated = NEW_CLI(handle_debugchan_deprecated, "Enable debugging on channel");
968 static struct ast_cli_entry cli_module_load_deprecated = NEW_CLI(handle_load_deprecated, "Load a module");
969 static struct ast_cli_entry cli_module_reload_deprecated = NEW_CLI(handle_reload_deprecated, "reload modules by name");
970 static struct ast_cli_entry cli_module_unload_deprecated = NEW_CLI(handle_unload_deprecated, "unload modules by name");
972 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
974 static struct ast_cli_entry cli_cli[] = {
975 /* Deprecated, but preferred command is now consolidated (and already has a deprecated command for it). */
976 NEW_CLI(handle_nodebugchan_deprecated, "Disable debugging on channel(s)"),
978 NEW_CLI(handle_chanlist, "Display information on channels"),
980 { { "core", "show", "channel", NULL },
981 handle_showchan, "Display information on a specific channel",
982 showchan_help, complete_ch_4 },
984 NEW_CLI(handle_core_set_debug_channel, "Enable/disable debugging on a channel",
985 .deprecate_cmd = &cli_debug_channel_deprecated),
987 NEW_CLI(handle_verbose, "Set level of debug/verbose chattiness"),
989 { { "group", "show", "channels", NULL },
990 group_show_channels, "Display active channels with group(s)",
991 group_show_channels_help },
993 NEW_CLI(handle_help, "Display help list, or specific help on a command"),
995 { { "logger", "mute", NULL },
996 handle_logger_mute, "Toggle logging output to a console",
999 NEW_CLI(handle_modlist, "List modules and info"),
1001 NEW_CLI(handle_load, "Load a module by name", .deprecate_cmd = &cli_module_load_deprecated),
1003 NEW_CLI(handle_reload, "Reload configuration", .deprecate_cmd = &cli_module_reload_deprecated),
1005 NEW_CLI(handle_unload, "Unload a module by name", .deprecate_cmd = &cli_module_unload_deprecated ),
1007 NEW_CLI(handle_showuptime, "Show uptime information"),
1009 { { "soft", "hangup", NULL },
1010 handle_softhangup, "Request a hangup on a given channel",
1011 softhangup_help, complete_ch_3 },
1015 * Some regexp characters in cli arguments are reserved and used as separators.
1017 static const char cli_rsvd[] = "[]{}|*%";
1020 * initialize the _full_cmd string and related parameters,
1021 * return 0 on success, -1 on error.
1023 static int set_full_cmd(struct ast_cli_entry *e)
1028 ast_join(buf, sizeof(buf), e->cmda);
1029 e->_full_cmd = ast_strdup(buf);
1030 if (!e->_full_cmd) {
1031 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
1034 e->cmdlen = strcspn(e->_full_cmd, cli_rsvd);
1035 for (i = 0; e->cmda[i]; i++)
1041 /*! \brief initialize the _full_cmd string in * each of the builtins. */
1042 void ast_builtins_init(void)
1044 struct ast_cli_entry *e;
1046 for (e = builtins; e->cmda[0] != NULL; e++)
1049 ast_cli_register_multiple(cli_cli, sizeof(cli_cli) / sizeof(struct ast_cli_entry));
1053 * We have two sets of commands: builtins are stored in a
1054 * NULL-terminated array of ast_cli_entry, whereas external
1055 * commands are in a list.
1056 * When navigating, we need to keep two pointers and get
1057 * the next one in lexicographic order. For the purpose,
1058 * we use a structure.
1061 struct cli_iterator {
1062 struct ast_cli_entry *builtins;
1063 struct ast_cli_entry *helpers;
1066 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
1068 struct ast_cli_entry *e;
1070 if (i->builtins == NULL && i->helpers == NULL) {
1072 i->builtins = builtins;
1073 i->helpers = AST_LIST_FIRST(&helpers);
1075 e = i->builtins; /* temporary */
1076 if (!e->cmda[0] || (i->helpers &&
1077 strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
1081 i->helpers = AST_LIST_NEXT(e, list);
1082 } else { /* use builtin. e is already set */
1083 (i->builtins)++; /* move to next */
1089 * match a word in the CLI entry.
1090 * returns -1 on mismatch, 0 on match of an optional word,
1091 * 1 on match of a full word.
1093 * The pattern can be
1094 * any_word match for equal
1095 * [foo|bar|baz] optionally, one of these words
1096 * {foo|bar|baz} exactly, one of these words
1099 static int word_match(const char *cmd, const char *cli_word)
1104 if (ast_strlen_zero(cmd) || ast_strlen_zero(cli_word))
1106 if (!strchr(cli_rsvd, cli_word[0])) /* normal match */
1107 return (strcasecmp(cmd, cli_word) == 0) ? 1 : -1;
1108 /* regexp match, takes [foo|bar] or {foo|bar} */
1110 /* wildcard match - will extend in the future */
1111 if (l > 0 && cli_word[0] == '%') {
1112 return 1; /* wildcard */
1114 pos = strcasestr(cli_word, cmd);
1115 if (pos == NULL) /* not found, say ok if optional */
1116 return cli_word[0] == '[' ? 0 : -1;
1117 if (pos == cli_word) /* no valid match at the beginning */
1119 if (strchr(cli_rsvd, pos[-1]) && strchr(cli_rsvd, pos[l]))
1120 return 1; /* valid match */
1121 return -1; /* not found */
1124 /*! \brief if word is a valid prefix for token, returns the pos-th
1125 * match as a malloced string, or NULL otherwise.
1126 * Always tell in *actual how many matches we got.
1128 static char *is_prefix(const char *word, const char *token,
1129 int pos, int *actual)
1135 if (ast_strlen_zero(token))
1137 if (ast_strlen_zero(word))
1138 word = ""; /* dummy */
1140 if (strcspn(word, cli_rsvd) != lw)
1141 return NULL; /* no match if word has reserved chars */
1142 if (strchr(cli_rsvd, token[0]) == NULL) { /* regular match */
1143 if (strncasecmp(token, word, lw)) /* no match */
1146 return (pos != 0) ? NULL : ast_strdup(token);
1148 /* now handle regexp match */
1150 /* Wildcard always matches, so we never do is_prefix on them */
1152 t1 = ast_strdupa(token + 1); /* copy, skipping first char */
1153 while (pos >= 0 && (s = strsep(&t1, cli_rsvd)) && *s) {
1154 if (*s == '%') /* wildcard */
1156 if (strncasecmp(s, word, lw)) /* no match */
1160 return ast_strdup(s);
1166 * \brief locate a cli command in the 'helpers' list (which must be locked).
1167 * exact has 3 values:
1168 * 0 returns if the search key is equal or longer than the entry.
1169 * note that trailing optional arguments are skipped.
1170 * -1 true if the mismatch is on the last word XXX not true!
1171 * 1 true only on complete, exact match.
1173 * The search compares word by word taking care of regexps in e->cmda
1175 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1177 int matchlen = -1; /* length of longest match so far */
1178 struct ast_cli_entry *cand = NULL, *e=NULL;
1179 struct cli_iterator i = { NULL, NULL};
1181 while ( (e = cli_next(&i)) ) {
1182 /* word-by word regexp comparison */
1183 char * const *src = cmds;
1184 char * const *dst = e->cmda;
1186 for (;; dst++, src += n) {
1187 n = word_match(*src, *dst);
1191 if (ast_strlen_zero(*dst) || ((*dst)[0] == '[' && ast_strlen_zero(dst[1]))) {
1192 /* no more words in 'e' */
1193 if (ast_strlen_zero(*src)) /* exact match, cannot do better */
1195 /* Here, cmds has more words than the entry 'e' */
1196 if (match_type != 0) /* but we look for almost exact match... */
1197 continue; /* so we skip this one. */
1198 /* otherwise we like it (case 0) */
1199 } else { /* still words in 'e' */
1200 if (ast_strlen_zero(*src))
1201 continue; /* cmds is shorter than 'e', not good */
1202 /* Here we have leftover words in cmds and 'e',
1203 * but there is a mismatch. We only accept this one if match_type == -1
1204 * and this is the last word for both.
1206 if (match_type != -1 || !ast_strlen_zero(src[1]) ||
1207 !ast_strlen_zero(dst[1])) /* not the one we look for */
1209 /* good, we are in case match_type == -1 and mismatch on last word */
1211 if (src - cmds > matchlen) { /* remember the candidate */
1212 matchlen = src - cmds;
1216 return e ? e : cand;
1219 static char *find_best(char *argv[])
1221 static char cmdline[80];
1223 /* See how close we get, then print the candidate */
1224 char *myargv[AST_MAX_CMD_LEN];
1225 for (x=0;x<AST_MAX_CMD_LEN;x++)
1227 AST_LIST_LOCK(&helpers);
1228 for (x=0;argv[x];x++) {
1229 myargv[x] = argv[x];
1230 if (!find_cli(myargv, -1))
1233 AST_LIST_UNLOCK(&helpers);
1234 ast_join(cmdline, sizeof(cmdline), myargv);
1238 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1240 if (e->deprecate_cmd) {
1241 __ast_cli_unregister(e->deprecate_cmd, e);
1244 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1246 AST_LIST_LOCK(&helpers);
1247 AST_LIST_REMOVE(&helpers, e, list);
1248 AST_LIST_UNLOCK(&helpers);
1249 ast_free(e->_full_cmd);
1250 e->_full_cmd = NULL;
1251 if (e->new_handler) {
1252 /* this is a new-style entry. Reset fields and free memory. */
1253 bzero((char **)(e->cmda), sizeof(e->cmda));
1254 ast_free(e->command);
1262 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1264 struct ast_cli_entry *cur;
1265 int i, lf, ret = -1;
1267 if (e->handler == NULL) { /* new style entry, run the handler to init fields */
1268 struct ast_cli_args a; /* fake argument */
1269 char **dst = (char **)e->cmda; /* need to cast as the entry is readonly */
1272 bzero (&a, sizeof(a));
1273 e->new_handler(e, CLI_INIT, &a);
1274 /* XXX check that usage and command are filled up */
1275 s = ast_skip_blanks(e->command);
1276 s = e->command = ast_strdup(s);
1277 for (i=0; !ast_strlen_zero(s) && i < AST_MAX_CMD_LEN-1; i++) {
1278 *dst++ = s; /* store string */
1279 s = ast_skip_nonblanks(s);
1280 if (*s == '\0') /* we are done */
1283 s = ast_skip_blanks(s);
1287 if (set_full_cmd(e))
1289 AST_LIST_LOCK(&helpers);
1291 if (find_cli(e->cmda, 1)) {
1292 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", e->_full_cmd);
1293 ast_free(e->_full_cmd);
1294 e->_full_cmd = NULL;
1301 e->summary = ed->summary;
1302 e->usage = ed->usage;
1303 /* XXX If command A deprecates command B, and command B deprecates command C...
1304 Do we want to show command A or command B when telling the user to use new syntax?
1305 This currently would show command A.
1306 To show command B, you just need to always use ed->_full_cmd.
1308 e->_deprecated_by = S_OR(ed->_deprecated_by, ed->_full_cmd);
1312 AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1313 int len = cur->cmdlen;
1316 if (strncasecmp(e->_full_cmd, cur->_full_cmd, len) < 0) {
1317 AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list);
1321 AST_LIST_TRAVERSE_SAFE_END;
1324 AST_LIST_INSERT_TAIL(&helpers, e, list);
1325 ret = 0; /* success */
1328 AST_LIST_UNLOCK(&helpers);
1330 if (e->deprecate_cmd) {
1331 /* This command deprecates another command. Register that one also. */
1332 __ast_cli_register(e->deprecate_cmd, e);
1338 /* wrapper function, so we can unregister deprecated commands recursively */
1339 int ast_cli_unregister(struct ast_cli_entry *e)
1341 return __ast_cli_unregister(e, NULL);
1344 /* wrapper function, so we can register deprecated commands recursively */
1345 int ast_cli_register(struct ast_cli_entry *e)
1347 return __ast_cli_register(e, NULL);
1351 * register/unregister an array of entries.
1353 int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1357 for (i = 0; i < len; i++)
1358 res |= ast_cli_register(e + i);
1363 int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1367 for (i = 0; i < len; i++)
1368 res |= ast_cli_unregister(e + i);
1374 /*! \brief helper for final part of
1375 * handle_help. if locked = 0 it's just "help_workhorse",
1376 * otherwise assume the list is already locked and print
1377 * an error message if not found.
1379 static char *help1(int fd, char *match[], int locked)
1381 char matchstr[80] = "";
1382 struct ast_cli_entry *e;
1385 struct cli_iterator i = { NULL, NULL};
1388 ast_join(matchstr, sizeof(matchstr), match);
1389 len = strlen(matchstr);
1392 AST_LIST_LOCK(&helpers);
1393 while ( (e = cli_next(&i)) ) {
1394 /* Hide commands that start with '_' */
1395 if (e->_full_cmd[0] == '_')
1397 /* Hide commands that are marked as deprecated. */
1400 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1402 ast_cli(fd, "%30.30s %s\n", e->_full_cmd, S_OR(e->summary, "<no description available>"));
1406 AST_LIST_UNLOCK(&helpers);
1407 if (!locked && !found && matchstr[0])
1408 ast_cli(fd, "No such command '%s'.\n", matchstr);
1412 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1415 struct ast_cli_entry *my_e;
1417 if (cmd == CLI_INIT) {
1418 e->command = "help";
1420 "Usage: help [topic]\n"
1421 " When called with a topic as an argument, displays usage\n"
1422 " information on the given command. If called without a\n"
1423 " topic, it provides a list of commands.\n";
1426 } else if (cmd == CLI_GENERATE) {
1427 /* skip first 4 or 5 chars, "help " */
1428 int l = strlen(a->line);
1432 /* XXX watch out, should stop to the non-generator parts */
1433 return __ast_cli_generator(a->line + l, a->word, a->n, 0);
1436 return help1(a->fd, NULL, 0);
1438 AST_LIST_LOCK(&helpers);
1439 my_e = find_cli(a->argv + 1, 1); /* try exact match first */
1441 return help1(a->fd, a->argv + 1, 1 /* locked */);
1443 ast_cli(a->fd, "%s", my_e->usage);
1445 ast_join(fullcmd, sizeof(fullcmd), a->argv+1);
1446 ast_cli(a->fd, "No help text available for '%s'.\n", fullcmd);
1448 AST_LIST_UNLOCK(&helpers);
1449 return RESULT_SUCCESS;
1452 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1461 if (trailingwhitespace == NULL)
1462 trailingwhitespace = &dummy;
1463 *trailingwhitespace = 0;
1464 if (s == NULL) /* invalid, though! */
1466 /* make a copy to store the parsed string */
1467 if (!(dup = ast_strdup(s)))
1471 /* scan the original string copying into cur when needed */
1474 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1477 if (*s == '"' && !escaped) {
1479 if (quoted && whitespace) {
1480 /* start a quoted string from previous whitespace: new argument */
1484 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1485 /* If we are not already in whitespace, and not in a quoted string or
1486 processing an escape sequence, and just entered whitespace, then
1487 finalize the previous argument and remember that we are in whitespace
1493 } else if (*s == '\\' && !escaped) {
1497 /* we leave whitespace, and are not quoted. So it's a new argument */
1505 /* Null terminate */
1507 /* XXX put a NULL in the last argument, because some functions that take
1508 * the array may want a null-terminated array.
1509 * argc still reflects the number of non-NULL entries.
1513 *trailingwhitespace = whitespace;
1517 /*! \brief Return the number of unique matches for the generator */
1518 int ast_cli_generatornummatches(const char *text, const char *word)
1520 int matches = 0, i = 0;
1521 char *buf = NULL, *oldbuf = NULL;
1523 while ((buf = ast_cli_generator(text, word, i++))) {
1524 if (!oldbuf || strcmp(buf,oldbuf))
1535 char **ast_cli_completion_matches(const char *text, const char *word)
1537 char **match_list = NULL, *retstr, *prevstr;
1538 size_t match_list_len, max_equal, which, i;
1541 /* leave entry 0 free for the longest common substring */
1543 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1544 if (matches + 1 >= match_list_len) {
1545 match_list_len <<= 1;
1546 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1549 match_list[++matches] = retstr;
1553 return match_list; /* NULL */
1555 /* Find the longest substring that is common to all results
1556 * (it is a candidate for completion), and store a copy in entry 0.
1558 prevstr = match_list[1];
1559 max_equal = strlen(prevstr);
1560 for (which = 2; which <= matches; which++) {
1561 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1566 if (!(retstr = ast_malloc(max_equal + 1)))
1569 ast_copy_string(retstr, match_list[1], max_equal + 1);
1570 match_list[0] = retstr;
1572 /* ensure that the array is NULL terminated */
1573 if (matches + 1 >= match_list_len) {
1574 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1577 match_list[matches + 1] = NULL;
1582 /*! \brief returns true if there are more words to match */
1583 static int more_words (char * const *dst)
1586 for (i = 0; dst[i]; i++) {
1587 if (dst[i][0] != '[')
1594 * generate the entry at position 'state'
1596 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1598 char *argv[AST_MAX_ARGS];
1599 struct ast_cli_entry *e;
1600 struct cli_iterator i = { NULL, NULL };
1601 int x = 0, argindex, matchlen;
1604 char matchstr[80] = "";
1606 /* Split the argument into an array of words */
1607 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1609 if (!dup) /* malloc error */
1612 /* Compute the index of the last argument (could be an empty string) */
1613 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1615 /* rebuild the command, ignore terminating white space and flatten space */
1616 ast_join(matchstr, sizeof(matchstr)-1, argv);
1617 matchlen = strlen(matchstr);
1619 strcat(matchstr, " "); /* XXX */
1624 AST_LIST_LOCK(&helpers);
1625 while ( (e = cli_next(&i)) ) {
1626 /* XXX repeated code */
1627 int src = 0, dst = 0, n = 0;
1630 * Try to match words, up to and excluding the last word, which
1631 * is either a blank or something that we want to extend.
1633 for (;src < argindex; dst++, src += n) {
1634 n = word_match(argv[src], e->cmda[dst]);
1639 if (src != argindex && more_words(e->cmda + dst)) /* not a match */
1641 ret = is_prefix(argv[src], e->cmda[dst], state - matchnum, &n);
1642 matchnum += n; /* this many matches here */
1645 * argv[src] is a valid prefix of the next word in this
1646 * command. If this is also the correct entry, return it.
1648 if (matchnum > state)
1652 } else if (ast_strlen_zero(e->cmda[dst])) {
1654 * This entry is a prefix of the command string entered
1655 * (only one entry in the list should have this property).
1656 * Run the generator if one is available. In any case we are done.
1659 ret = e->generator(matchstr, word, argindex, state - matchnum);
1660 else if (e->new_handler) { /* new style command */
1661 struct ast_cli_args a = {
1662 .line = matchstr, .word = word,
1664 .n = state - matchnum };
1665 ret = e->new_handler(e, CLI_GENERATE, &a);
1672 AST_LIST_UNLOCK(&helpers);
1677 char *ast_cli_generator(const char *text, const char *word, int state)
1679 return __ast_cli_generator(text, word, state, 1);
1682 int ast_cli_command(int fd, const char *s)
1684 char *args[AST_MAX_ARGS + 1];
1685 struct ast_cli_entry *e;
1688 char *dup = parse_args(s, &x, args + 1, AST_MAX_ARGS, NULL);
1693 if (x < 1) /* We need at least one entry, otherwise ignore */
1696 AST_LIST_LOCK(&helpers);
1697 e = find_cli(args + 1, 0);
1699 ast_atomic_fetchadd_int(&e->inuse, 1);
1700 AST_LIST_UNLOCK(&helpers);
1702 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(args + 1));
1706 * Within the handler, argv[-1] contains a pointer to the ast_cli_entry.
1707 * Remember that the array returned by parse_args is NULL-terminated.
1709 args[0] = (char *)e;
1711 if (!e->new_handler) /* old style */
1712 res = e->handler(fd, x, args + 1);
1714 struct ast_cli_args a = {
1715 .fd = fd, .argc = x, .argv = args+1 };
1716 char *retval = e->new_handler(e, CLI_HANDLER, &a);
1718 if (retval == CLI_SUCCESS)
1719 res = RESULT_SUCCESS;
1720 else if (retval == CLI_SHOWUSAGE)
1721 res = RESULT_SHOWUSAGE;
1723 res = RESULT_FAILURE;
1726 case RESULT_SHOWUSAGE:
1727 ast_cli(fd, "%s", S_OR(e->usage, "Invalid usage, but no usage information available.\n"));
1728 AST_LIST_LOCK(&helpers);
1730 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);
1731 AST_LIST_UNLOCK(&helpers);
1733 case RESULT_FAILURE:
1734 ast_cli(fd, "Command '%s' failed.\n", s);
1737 AST_LIST_LOCK(&helpers);
1738 if (e->deprecated == 1) {
1739 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);
1742 AST_LIST_UNLOCK(&helpers);
1745 ast_atomic_fetchadd_int(&e->inuse, -1);