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 extern unsigned long global_fin, global_fout;
54 AST_THREADSTORAGE(ast_cli_buf);
56 /*! \brief Initial buffer size for resulting strings in ast_cli() */
57 #define AST_CLI_INITLEN 256
59 void ast_cli(int fd, char *fmt, ...)
62 struct ast_dynamic_str *buf;
65 if (!(buf = ast_dynamic_str_thread_get(&ast_cli_buf, AST_CLI_INITLEN)))
69 res = ast_dynamic_str_thread_set_va(&buf, 0, &ast_cli_buf, fmt, ap);
72 if (res != AST_DYNSTR_BUILD_FAILED)
73 ast_carefulwrite(fd, buf->str, strlen(buf->str), 100);
76 static AST_LIST_HEAD_STATIC(helpers, ast_cli_entry);
78 static char load_help[] =
79 "Usage: load <module name>\n"
80 " Loads the specified module into Asterisk.\n";
82 static char unload_help[] =
83 "Usage: unload [-f|-h] <module name>\n"
84 " Unloads the specified module from Asterisk. The -f\n"
85 " option causes the module to be unloaded even if it is\n"
86 " in use (may cause a crash) and the -h module causes the\n"
87 " module to be unloaded even if the module says it cannot, \n"
88 " which almost always will cause a crash.\n";
90 static char help_help[] =
91 "Usage: help [topic]\n"
92 " When called with a topic as an argument, displays usage\n"
93 " information on the given command. If called without a\n"
94 " topic, it provides a list of commands.\n";
96 static char chanlist_help[] =
97 "Usage: core show channels [concise|verbose]\n"
98 " Lists currently defined channels and some information about them. If\n"
99 " 'concise' is specified, the format is abridged and in a more easily\n"
100 " machine parsable format. If 'verbose' is specified, the output includes\n"
101 " more and longer fields.\n";
103 static char reload_help[] =
104 "Usage: reload [module ...]\n"
105 " Reloads configuration files for all listed modules which support\n"
106 " reloading, or for all supported modules if none are listed.\n";
108 static char verbose_help[] =
109 "Usage: core set verbose <level>\n"
110 " Sets level of verbose messages to be displayed. 0 means\n"
111 " no messages should be displayed. Equivalent to -v[v[v...]]\n"
114 static char debug_help[] =
115 "Usage: core set debug <level> [filename]\n"
116 " Sets level of core debug messages to be displayed. 0 means\n"
117 " no messages should be displayed. Equivalent to -d[d[d...]]\n"
118 " on startup. If filename is specified, debugging will be\n"
119 " limited to just that file.\n";
121 static char nodebug_help[] =
122 "Usage: core set no debug\n"
123 " Turns off core debug messages.\n";
125 static char logger_mute_help[] =
126 "Usage: logger mute\n"
127 " Disables logging output to the current console, making it possible to\n"
128 " gather information without being disturbed by scrolling lines.\n";
130 static char softhangup_help[] =
131 "Usage: soft hangup <channel>\n"
132 " Request that a channel be hung up. The hangup takes effect\n"
133 " the next time the driver reads or writes from the channel\n";
135 static char group_show_channels_help[] =
136 "Usage: group show channels [pattern]\n"
137 " Lists all currently active channels with channel group(s) specified.\n"
138 " Optional regular expression pattern is matched to group names for each\n"
141 static int handle_load(int fd, int argc, char *argv[])
144 return RESULT_SHOWUSAGE;
145 if (ast_load_resource(argv[1])) {
146 ast_cli(fd, "Unable to load module %s\n", argv[1]);
147 return RESULT_FAILURE;
149 return RESULT_SUCCESS;
152 static int handle_reload(int fd, int argc, char *argv[])
157 return RESULT_SHOWUSAGE;
159 for (x=1;x<argc;x++) {
160 res = ast_module_reload(argv[x]);
163 ast_cli(fd, "No such module '%s'\n", argv[x]);
166 ast_cli(fd, "Module '%s' does not support reload\n", argv[x]);
171 ast_module_reload(NULL);
172 return RESULT_SUCCESS;
175 static int handle_verbose(int fd, int argc, char *argv[])
177 int oldval = option_verbose;
181 if ((argc < 4) || (argc > 5))
182 return RESULT_SHOWUSAGE;
184 if (!strcasecmp(argv[3], "atleast"))
189 return RESULT_SHOWUSAGE;
191 option_verbose = atoi(argv[3]);
194 return RESULT_SHOWUSAGE;
196 newlevel = atoi(argv[4]);
197 if (newlevel > option_verbose)
198 option_verbose = newlevel;
200 if (oldval > 0 && option_verbose == 0)
201 ast_cli(fd, "Verbosity is now OFF\n");
202 else if (option_verbose > 0) {
203 if (oldval == option_verbose)
204 ast_cli(fd, "Verbosity is at least %d\n", option_verbose);
206 ast_cli(fd, "Verbosity was %d and is now %d\n", oldval, option_verbose);
209 return RESULT_SUCCESS;
212 static int handle_debug(int fd, int argc, char *argv[])
214 int oldval = option_debug;
217 char *filename = '\0';
219 if ((argc < 4) || (argc > 6))
220 return RESULT_SHOWUSAGE;
222 if (!strcasecmp(argv[3], "atleast"))
227 return RESULT_SHOWUSAGE;
229 if (sscanf(argv[3], "%d", &newlevel) != 1)
230 return RESULT_SHOWUSAGE;
233 debug_filename[0] = '\0';
236 ast_copy_string(debug_filename, filename, sizeof(debug_filename));
239 option_debug = newlevel;
241 if (argc < 5 || argc > 6)
242 return RESULT_SHOWUSAGE;
244 if (sscanf(argv[4], "%d", &newlevel) != 1)
245 return RESULT_SHOWUSAGE;
248 debug_filename[0] = '\0';
251 ast_copy_string(debug_filename, filename, sizeof(debug_filename));
254 if (newlevel > option_debug)
255 option_debug = newlevel;
258 if (oldval > 0 && option_debug == 0)
259 ast_cli(fd, "Core debug is now OFF\n");
260 else if (option_debug > 0) {
262 if (oldval == option_debug)
263 ast_cli(fd, "Core debug is at least %d, file '%s'\n", option_debug, filename);
265 ast_cli(fd, "Core debug was %d and is now %d, file '%s'\n", oldval, option_debug, filename);
267 if (oldval == option_debug)
268 ast_cli(fd, "Core debug is at least %d\n", option_debug);
270 ast_cli(fd, "Core debug was %d and is now %d\n", oldval, option_debug);
274 return RESULT_SUCCESS;
277 static int handle_nodebug(int fd, int argc, char *argv[])
279 int oldval = option_debug;
281 return RESULT_SHOWUSAGE;
284 debug_filename[0] = '\0';
287 ast_cli(fd, "Core debug is now OFF\n");
288 return RESULT_SUCCESS;
291 static int handle_logger_mute(int fd, int argc, char *argv[])
294 return RESULT_SHOWUSAGE;
295 ast_console_toggle_mute(fd);
296 return RESULT_SUCCESS;
299 static int handle_unload(int fd, int argc, char *argv[])
302 int force=AST_FORCE_SOFT;
304 return RESULT_SHOWUSAGE;
305 for (x=1;x<argc;x++) {
306 if (argv[x][0] == '-') {
309 force = AST_FORCE_FIRM;
312 force = AST_FORCE_HARD;
315 return RESULT_SHOWUSAGE;
317 } else if (x != argc - 1)
318 return RESULT_SHOWUSAGE;
319 else if (ast_unload_resource(argv[x], force)) {
320 ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
321 return RESULT_FAILURE;
324 return RESULT_SUCCESS;
327 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
328 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
330 AST_MUTEX_DEFINE_STATIC(climodentrylock);
331 static int climodentryfd = -1;
333 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
335 /* Comparing the like with the module */
336 if (strcasestr(module, like) ) {
337 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
343 static char modlist_help[] =
344 "Usage: core show modules [like keyword]\n"
345 " Shows Asterisk modules currently in use, and usage statistics.\n";
347 static char uptime_help[] =
348 "Usage: core show uptime [seconds]\n"
349 " Shows Asterisk uptime information.\n"
350 " The seconds word returns the uptime in seconds only.\n";
352 static void print_uptimestr(int fd, time_t timeval, const char *prefix, int printsec)
354 int x; /* the main part - years, weeks, etc. */
355 char timestr[256]="", *s = timestr;
356 size_t maxbytes = sizeof(timestr);
359 #define MINUTE (SECOND*60)
360 #define HOUR (MINUTE*60)
361 #define DAY (HOUR*24)
363 #define YEAR (DAY*365)
364 #define ESS(x) ((x == 1) ? "" : "s") /* plural suffix */
365 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
366 if (timeval < 0) /* invalid, nothing to show */
368 if (printsec) { /* plain seconds output */
369 ast_build_string(&s, &maxbytes, "%lu", (u_long)timeval);
370 timeval = 0; /* bypass the other cases */
372 if (timeval > YEAR) {
373 x = (timeval / YEAR);
374 timeval -= (x * YEAR);
375 ast_build_string(&s, &maxbytes, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval));
377 if (timeval > WEEK) {
378 x = (timeval / WEEK);
379 timeval -= (x * WEEK);
380 ast_build_string(&s, &maxbytes, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval));
384 timeval -= (x * DAY);
385 ast_build_string(&s, &maxbytes, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval));
387 if (timeval > HOUR) {
388 x = (timeval / HOUR);
389 timeval -= (x * HOUR);
390 ast_build_string(&s, &maxbytes, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval));
392 if (timeval > MINUTE) {
393 x = (timeval / MINUTE);
394 timeval -= (x * MINUTE);
395 ast_build_string(&s, &maxbytes, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval));
399 ast_build_string(&s, &maxbytes, "%d second%s ", x, ESS(x));
400 if (timestr[0] != '\0')
401 ast_cli(fd, "%s: %s\n", prefix, timestr);
404 static int handle_showuptime(int fd, int argc, char *argv[])
406 /* 'show uptime [seconds]' */
407 time_t curtime = time(NULL);
408 int printsec = (argc == 4 && !strcasecmp(argv[3],"seconds"));
410 if (argc != 3 && !printsec)
411 return RESULT_SHOWUSAGE;
413 print_uptimestr(fd, curtime - ast_startuptime, "System uptime", printsec);
414 if (ast_lastreloadtime)
415 print_uptimestr(fd, curtime - ast_lastreloadtime, "Last reload", printsec);
416 return RESULT_SUCCESS;
419 /* core show modules [like keyword] */
420 static int handle_modlist(int fd, int argc, char *argv[])
423 if (argc != 3 && argc != 5)
424 return RESULT_SHOWUSAGE;
425 else if (argc == 5) {
426 if (strcmp(argv[3],"like"))
427 return RESULT_SHOWUSAGE;
431 ast_mutex_lock(&climodentrylock);
432 climodentryfd = fd; /* global, protected by climodentrylock */
433 ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
434 ast_cli(fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
436 ast_mutex_unlock(&climodentrylock);
437 return RESULT_SUCCESS;
439 #undef MODLIST_FORMAT
440 #undef MODLIST_FORMAT2
442 /* core show channels [concise|verbose] */
443 static int handle_chanlist(int fd, int argc, char *argv[])
445 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
446 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
447 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s\n"
448 #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"
449 #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"
451 struct ast_channel *c = NULL;
452 char durbuf[10] = "-";
456 int durh, durm, durs;
457 int numchans = 0, concise = 0, verbose = 0;
460 concise = !strcasecmp(argv[2],"concise");
461 verbose = !strcasecmp(argv[2],"verbose");
464 if (argc < 3 || argc > 4 || (argc == 4 && !concise && !verbose))
465 return RESULT_SHOWUSAGE;
467 if (!concise && !verbose)
468 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
470 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
471 "CallerID", "Duration", "Accountcode", "BridgedTo");
473 while ((c = ast_channel_walk_locked(c)) != NULL) {
474 struct ast_channel *bc = ast_bridged_channel(c);
475 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
476 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
478 durh = duration / 3600;
479 durm = (duration % 3600) / 60;
480 durs = duration % 60;
481 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
483 snprintf(durbuf, sizeof(durbuf), "%d", duration);
489 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
490 c->appl ? c->appl : "(None)",
491 S_OR(c->data, ""), /* XXX different from verbose ? */
492 S_OR(c->cid.cid_num, ""),
493 S_OR(c->accountcode, ""),
496 bc ? bc->name : "(None)");
497 } else if (verbose) {
498 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
499 c->appl ? c->appl : "(None)",
500 c->data ? S_OR(c->data, "(Empty)" ): "(None)",
501 S_OR(c->cid.cid_num, ""),
503 S_OR(c->accountcode, ""),
504 bc ? bc->name : "(None)");
506 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
507 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
509 strcpy(locbuf, "(None)");
511 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, c->data ? c->data : "");
513 strcpy(appdata, "(None)");
514 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
517 ast_channel_unlock(c);
520 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
522 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
523 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
524 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
526 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
528 return RESULT_SUCCESS;
531 #undef FORMAT_STRING2
532 #undef CONCISE_FORMAT_STRING
533 #undef VERBOSE_FORMAT_STRING
534 #undef VERBOSE_FORMAT_STRING2
537 static char showchan_help[] =
538 "Usage: channel show <channel>\n"
539 " Shows lots of information about the specified channel.\n";
541 static char debugchan_help[] =
542 "Usage: channel debug <channel>\n"
543 " Enables debugging on a specific channel.\n";
545 static char nodebugchan_help[] =
546 "Usage: channel nodebug <channel>\n"
547 " Disables debugging on a specific channel.\n";
549 static char commandcomplete_help[] =
550 "Usage: _command complete \"<line>\" text state\n"
551 " This function is used internally to help with command completion and should.\n"
552 " never be called by the user directly.\n";
554 static char commandnummatches_help[] =
555 "Usage: _command nummatches \"<line>\" text \n"
556 " This function is used internally to help with command completion and should.\n"
557 " never be called by the user directly.\n";
559 static char commandmatchesarray_help[] =
560 "Usage: _command matchesarray \"<line>\" text \n"
561 " This function is used internally to help with command completion and should.\n"
562 " never be called by the user directly.\n";
564 static int handle_softhangup(int fd, int argc, char *argv[])
566 struct ast_channel *c=NULL;
568 return RESULT_SHOWUSAGE;
569 c = ast_get_channel_by_name_locked(argv[2]);
571 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
572 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
573 ast_channel_unlock(c);
575 ast_cli(fd, "%s is not a known channel\n", argv[2]);
576 return RESULT_SUCCESS;
579 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
581 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
590 return RESULT_SHOWUSAGE;
591 if (!(buf = ast_malloc(buflen)))
592 return RESULT_FAILURE;
594 matches = ast_cli_completion_matches(argv[2], argv[3]);
596 for (x=0; matches[x]; x++) {
597 matchlen = strlen(matches[x]) + 1;
598 if (len + matchlen >= buflen) {
599 buflen += matchlen * 3;
601 if (!(buf = ast_realloc(obuf, buflen)))
602 /* Memory allocation failure... Just free old buffer and be done */
606 len += sprintf( buf + len, "%s ", matches[x]);
614 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
617 ast_cli(fd, "NULL\n");
619 return RESULT_SUCCESS;
624 static int handle_commandnummatches(int fd, int argc, char *argv[])
629 return RESULT_SHOWUSAGE;
631 matches = ast_cli_generatornummatches(argv[2], argv[3]);
633 ast_cli(fd, "%d", matches);
635 return RESULT_SUCCESS;
638 static int handle_commandcomplete(int fd, int argc, char *argv[])
643 return RESULT_SHOWUSAGE;
644 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
649 ast_cli(fd, "NULL\n");
650 return RESULT_SUCCESS;
653 /* XXX todo: merge next two functions!!! */
654 static int handle_debugchan(int fd, int argc, char *argv[])
656 struct ast_channel *c=NULL;
659 /* 'debug channel {all|chan_id}' */
661 return RESULT_SHOWUSAGE;
663 is_all = !strcasecmp("all", argv[3]);
665 global_fin |= DEBUGCHAN_FLAG;
666 global_fout |= DEBUGCHAN_FLAG;
667 c = ast_channel_walk_locked(NULL);
669 c = ast_get_channel_by_name_locked(argv[3]);
671 ast_cli(fd, "No such channel %s\n", argv[3]);
674 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
675 c->fin |= DEBUGCHAN_FLAG;
676 c->fout |= DEBUGCHAN_FLAG;
677 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
679 ast_channel_unlock(c);
682 c = ast_channel_walk_locked(c);
684 ast_cli(fd, "Debugging on new channels is enabled\n");
685 return RESULT_SUCCESS;
688 static int handle_nodebugchan(int fd, int argc, char *argv[])
690 struct ast_channel *c=NULL;
692 /* 'no debug channel {all|chan_id}' */
694 return RESULT_SHOWUSAGE;
695 is_all = !strcasecmp("all", argv[2]);
697 global_fin &= ~DEBUGCHAN_FLAG;
698 global_fout &= ~DEBUGCHAN_FLAG;
699 c = ast_channel_walk_locked(NULL);
701 c = ast_get_channel_by_name_locked(argv[2]);
703 ast_cli(fd, "No such channel %s\n", argv[2]);
706 if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
707 c->fin &= ~DEBUGCHAN_FLAG;
708 c->fout &= ~DEBUGCHAN_FLAG;
709 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
711 ast_channel_unlock(c);
714 c = ast_channel_walk_locked(c);
716 ast_cli(fd, "Debugging on new channels is disabled\n");
717 return RESULT_SUCCESS;
720 static int handle_showchan(int fd, int argc, char *argv[])
722 struct ast_channel *c=NULL;
726 char nf[256], wf[256], rf[256];
727 long elapsed_seconds=0;
728 int hour=0, min=0, sec=0;
731 return RESULT_SHOWUSAGE;
733 c = ast_get_channel_by_name_locked(argv[3]);
735 ast_cli(fd, "%s is not a known channel\n", argv[3]);
736 return RESULT_SUCCESS;
739 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
740 hour = elapsed_seconds / 3600;
741 min = (elapsed_seconds % 3600) / 60;
742 sec = elapsed_seconds % 60;
743 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
745 strcpy(cdrtime, "N/A");
752 " Caller ID Name: %s\n"
756 " NativeFormats: %s\n"
759 " WriteTranscode: %s\n"
760 " ReadTranscode: %s\n"
761 "1st File Descriptor: %d\n"
763 " Frames out: %d%s\n"
764 " Time to Hangup: %ld\n"
765 " Elapsed Time: %s\n"
766 " Direct Bridge: %s\n"
767 "Indirect Bridge: %s\n"
772 " Call Group: %llu\n"
773 " Pickup Group: %llu\n"
776 " Blocking in: %s\n",
777 c->name, c->tech->type, c->uniqueid,
778 S_OR(c->cid.cid_num, "(N/A)"),
779 S_OR(c->cid.cid_name, "(N/A)"),
780 S_OR(c->cid.cid_dnid, "(N/A)"), ast_state2str(c->_state), c->_state, c->rings,
781 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
782 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
783 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
784 c->writetrans ? "Yes" : "No",
785 c->readtrans ? "Yes" : "No",
787 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
788 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
789 (long)c->whentohangup,
790 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
791 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
792 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
793 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
795 if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
796 ast_cli(fd," Variables:\n%s\n",buf);
797 if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
798 ast_cli(fd," CDR Variables:\n%s\n",buf);
800 ast_channel_unlock(c);
801 return RESULT_SUCCESS;
805 * helper function to generate CLI matches from a fixed set of values.
806 * A NULL word is acceptable.
808 char *ast_cli_complete(const char *word, char *const choices[], int state)
810 int i, which = 0, len;
811 len = ast_strlen_zero(word) ? 0 : strlen(word);
813 for (i = 0; choices[i]; i++) {
814 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
815 return ast_strdup(choices[i]);
820 static char *complete_show_channels(const char *line, const char *word, int pos, int state)
822 static char *choices[] = { "concise", "verbose", NULL };
824 return (pos != 3) ? NULL : ast_cli_complete(word, choices, state);
827 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
829 struct ast_channel *c = NULL;
832 char notfound = '\0';
833 char *ret = ¬found; /* so NULL can break the loop */
838 wordlen = strlen(word);
840 while (ret == ¬found && (c = ast_channel_walk_locked(c))) {
841 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
842 ret = ast_strdup(c->name);
843 ast_channel_unlock(c);
845 return ret == ¬found ? NULL : ret;
848 static char *complete_ch_3(const char *line, const char *word, int pos, int state)
850 return ast_complete_channels(line, word, pos, state, 2);
853 static char *complete_ch_4(const char *line, const char *word, int pos, int state)
855 return ast_complete_channels(line, word, pos, state, 3);
858 static char *complete_ch_5(const char *line, const char *word, int pos, int state)
860 return ast_complete_channels(line, word, pos, state, 4);
863 static char *complete_mod_3_nr(const char *line, const char *word, int pos, int state)
865 return ast_module_helper(line, word, pos, state, 2, 0);
868 static char *complete_mod_3(const char *line, const char *word, int pos, int state)
870 return ast_module_helper(line, word, pos, state, 2, 1);
873 static char *complete_mod_4(const char *line, const char *word, int pos, int state)
875 return ast_module_helper(line, word, pos, state, 3, 0);
878 static char *complete_fn(const char *line, const char *word, int pos, int state)
887 ast_copy_string(filename, word, sizeof(filename));
889 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
891 c = filename_completion_function(filename, state);
893 if (c && word[0] != '/')
894 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
896 return c ? strdup(c) : c;
899 static int group_show_channels(int fd, int argc, char *argv[])
901 #define FORMAT_STRING "%-25s %-20s %-20s\n"
903 struct ast_channel *c = NULL;
905 struct ast_var_t *current;
906 struct varshead *headp;
910 if (argc < 3 || argc > 4)
911 return RESULT_SHOWUSAGE;
914 if (regcomp(®exbuf, argv[3], REG_EXTENDED | REG_NOSUB))
915 return RESULT_SHOWUSAGE;
919 ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
920 while ( (c = ast_channel_walk_locked(c)) != NULL) {
922 AST_LIST_TRAVERSE(headp,current,entries) {
923 if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
924 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
925 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
926 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
929 } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
930 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
931 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
937 ast_channel_unlock(c);
943 ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
944 return RESULT_SUCCESS;
948 static int handle_help(int fd, int argc, char *argv[]);
950 static char * complete_help(const char *text, const char *word, int pos, int state)
952 /* skip first 4 or 5 chars, "help "*/
953 int l = strlen(text);
958 /* XXX watch out, should stop to the non-generator parts */
959 return __ast_cli_generator(text, word, state, 0);
962 /* XXX Nothing in this array can currently be deprecated...
963 You have to change the way find_cli works in order to remove this array
964 I recommend doing this eventually...
966 static struct ast_cli_entry builtins[] = {
967 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
968 { { "_command", "complete", NULL },
969 handle_commandcomplete, "Command complete",
970 commandcomplete_help },
972 { { "_command", "nummatches", NULL },
973 handle_commandnummatches, "Returns number of command matches",
974 commandnummatches_help },
976 { { "_command", "matchesarray", NULL },
977 handle_commandmatchesarray, "Returns command matches array",
978 commandmatchesarray_help },
980 { { NULL }, NULL, NULL, NULL }
983 static struct ast_cli_entry cli_cli[] = {
984 { { "core", "show", "channels", NULL },
985 handle_chanlist, "Display information on channels",
986 chanlist_help, complete_show_channels },
988 { { "core", "show" "channel", NULL },
989 handle_showchan, "Display information on a specific channel",
990 showchan_help, complete_ch_4 },
992 { { "core", "debug", "channel", NULL },
993 handle_debugchan, "Enable debugging on a channel",
994 debugchan_help, complete_ch_4 },
996 { { "core", "no", "debug", "channel", NULL },
997 handle_nodebugchan, "Disable debugging on a channel",
998 nodebugchan_help, complete_ch_5 },
1000 { { "core", "set", "debug", NULL },
1001 handle_debug, "Set level of debug chattiness",
1004 { { "core", "set", "no", "debug", NULL },
1005 handle_nodebug, "Turns off debug chattiness",
1008 { { "core", "set", "verbose", NULL },
1009 handle_verbose, "Set level of verboseness",
1012 { { "group", "show", "channels", NULL },
1013 group_show_channels, "Display active channels with group(s)",
1014 group_show_channels_help },
1017 handle_help, "Display help list, or specific help on a command",
1018 help_help, complete_help },
1020 { { "logger", "mute", NULL },
1021 handle_logger_mute, "Toggle logging output to a console",
1024 { { "core", "show", "modules", NULL },
1025 handle_modlist, "List modules and info",
1028 { { "core", "show", "modules", "like", NULL },
1029 handle_modlist, "List modules and info",
1030 modlist_help, complete_mod_4 },
1033 handle_load, "Load a module by name",
1034 load_help, complete_fn },
1036 { { "reload", NULL },
1037 handle_reload, "Reload configuration",
1038 reload_help, complete_mod_3 },
1040 { { "unload", NULL },
1041 handle_unload, "Unload a module by name",
1042 unload_help, complete_mod_3_nr },
1044 { { "core", "show", "uptime", NULL },
1045 handle_showuptime, "Show uptime information",
1048 { { "soft", "hangup", NULL },
1049 handle_softhangup, "Request a hangup on a given channel",
1050 softhangup_help, complete_ch_3 },
1053 /*! \brief initialize the _full_cmd string in * each of the builtins. */
1054 void ast_builtins_init(void)
1056 struct ast_cli_entry *e;
1058 for (e = builtins; e->cmda[0] != NULL; e++) {
1060 ast_join(buf, sizeof(buf), e->cmda);
1061 e->_full_cmd = strdup(buf);
1063 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
1066 ast_cli_register_multiple(cli_cli, sizeof(cli_cli) / sizeof(struct ast_cli_entry));
1070 * We have two sets of commands: builtins are stored in a
1071 * NULL-terminated array of ast_cli_entry, whereas external
1072 * commands are in a list.
1073 * When navigating, we need to keep two pointers and get
1074 * the next one in lexicographic order. For the purpose,
1075 * we use a structure.
1078 struct cli_iterator {
1079 struct ast_cli_entry *builtins;
1080 struct ast_cli_entry *helpers;
1083 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
1085 struct ast_cli_entry *e;
1087 if (i->builtins == NULL && i->helpers == NULL) {
1089 i->builtins = builtins;
1090 i->helpers = AST_LIST_FIRST(&helpers);
1092 e = i->builtins; /* temporary */
1093 if (!e->cmda[0] || (i->helpers &&
1094 strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
1098 i->helpers = AST_LIST_NEXT(e, list);
1099 } else { /* use builtin. e is already set */
1100 (i->builtins)++; /* move to next */
1106 * \brief locate a cli command in the 'helpers' list (which must be locked).
1107 * exact has 3 values:
1108 * 0 returns if the search key is equal or longer than the entry.
1109 * -1 true if the mismatch is on the last word XXX not true!
1110 * 1 true only on complete, exact match.
1112 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1114 int matchlen = -1; /* length of longest match so far */
1115 struct ast_cli_entry *cand = NULL, *e=NULL;
1116 struct cli_iterator i = { NULL, NULL};
1118 while( (e = cli_next(&i)) ) {
1120 for (y = 0 ; cmds[y] && e->cmda[y]; y++) {
1121 if (strcasecmp(e->cmda[y], cmds[y]))
1124 if (e->cmda[y] == NULL) { /* no more words in candidate */
1125 if (cmds[y] == NULL) /* this is an exact match, cannot do better */
1127 /* here the search key is longer than the candidate */
1128 if (match_type != 0) /* but we look for almost exact match... */
1129 continue; /* so we skip this one. */
1130 /* otherwise we like it (case 0) */
1131 } else { /* still words in candidate */
1132 if (cmds[y] == NULL) /* search key is shorter, not good */
1134 /* if we get here, both words exist but there is a mismatch */
1135 if (match_type == 0) /* not the one we look for */
1137 if (match_type == 1) /* not the one we look for */
1139 if (cmds[y+1] != NULL || e->cmda[y+1] != NULL) /* not the one we look for */
1141 /* we are in case match_type == -1 and mismatch on last word */
1143 if (cand == NULL || y > matchlen) /* remember the candidate */
1146 return e ? e : cand;
1149 static char *find_best(char *argv[])
1151 static char cmdline[80];
1153 /* See how close we get, then print the candidate */
1154 char *myargv[AST_MAX_CMD_LEN];
1155 for (x=0;x<AST_MAX_CMD_LEN;x++)
1157 AST_LIST_LOCK(&helpers);
1158 for (x=0;argv[x];x++) {
1159 myargv[x] = argv[x];
1160 if (!find_cli(myargv, -1))
1163 AST_LIST_UNLOCK(&helpers);
1164 ast_join(cmdline, sizeof(cmdline), myargv);
1168 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1170 if (e->deprecate_cmd) {
1171 __ast_cli_unregister(e->deprecate_cmd, e);
1174 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1176 AST_LIST_LOCK(&helpers);
1177 AST_LIST_REMOVE(&helpers, e, list);
1178 AST_LIST_UNLOCK(&helpers);
1183 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1185 struct ast_cli_entry *cur;
1189 ast_join(fulle, sizeof(fulle), e->cmda);
1190 AST_LIST_LOCK(&helpers);
1192 if (find_cli(e->cmda, 1)) {
1193 AST_LIST_UNLOCK(&helpers);
1194 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1197 e->_full_cmd = ast_strdup(fulle);
1203 e->summary = ed->summary;
1204 e->usage = ed->usage;
1205 /* XXX If command A deprecates command B, and command B deprecates command C...
1206 Do we want to show command A or command B when telling the user to use new syntax?
1207 This currently would show command A.
1208 To show command B, you just need to always use ed->_full_cmd.
1210 e->_deprecated_by = S_OR(ed->_deprecated_by, ed->_full_cmd);
1216 AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1217 int len = strlen(cur->_full_cmd);
1220 if (strncasecmp(fulle, cur->_full_cmd, len) < 0) {
1221 AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list);
1225 AST_LIST_TRAVERSE_SAFE_END;
1228 AST_LIST_INSERT_TAIL(&helpers, e, list);
1229 ret = 0; /* success */
1232 AST_LIST_UNLOCK(&helpers);
1234 if (e->deprecate_cmd) {
1235 /* This command deprecates another command. Register that one also. */
1236 __ast_cli_register(e->deprecate_cmd, e);
1242 /* wrapper function, so we can unregister deprecated commands recursively */
1243 int ast_cli_unregister(struct ast_cli_entry *e)
1245 return __ast_cli_unregister(e, NULL);
1248 /* wrapper function, so we can register deprecated commands recursively */
1249 int ast_cli_register(struct ast_cli_entry *e)
1251 return __ast_cli_register(e, NULL);
1255 * register/unregister an array of entries.
1257 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1261 for (i = 0; i < len; i++)
1262 ast_cli_register(e + i);
1265 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1269 for (i = 0; i < len; i++)
1270 ast_cli_unregister(e + i);
1274 /*! \brief helper for help_workhorse and final part of
1275 * handle_help. if locked = 0 it's just help_workhorse,
1276 * otherwise assume the list is already locked and print
1277 * an error message if not found.
1279 static int help1(int fd, char *match[], int locked)
1281 char matchstr[80] = "";
1282 struct ast_cli_entry *e;
1285 struct cli_iterator i = { NULL, NULL};
1288 ast_join(matchstr, sizeof(matchstr), match);
1289 len = strlen(matchstr);
1292 AST_LIST_LOCK(&helpers);
1293 while ( (e = cli_next(&i)) ) {
1294 /* Hide commands that start with '_' */
1295 if (e->_full_cmd[0] == '_')
1297 /* Hide commands that are marked as deprecated. */
1300 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1302 ast_cli(fd, "%25.25s %s\n", e->_full_cmd, e->summary);
1305 AST_LIST_UNLOCK(&helpers);
1306 if (!locked && !found && matchstr[0])
1307 ast_cli(fd, "No such command '%s'.\n", matchstr);
1311 static int help_workhorse(int fd, char *match[])
1313 return help1(fd, match, 0 /* do not print errors */);
1316 static int handle_help(int fd, int argc, char *argv[])
1319 struct ast_cli_entry *e;
1322 return RESULT_SHOWUSAGE;
1324 return help_workhorse(fd, NULL);
1326 AST_LIST_LOCK(&helpers);
1327 e = find_cli(argv + 1, 1); /* try exact match first */
1329 return help1(fd, argv + 1, 1 /* locked */);
1331 ast_cli(fd, "%s", e->usage);
1333 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1334 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1336 AST_LIST_UNLOCK(&helpers);
1337 return RESULT_SUCCESS;
1340 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1348 *trailingwhitespace = 0;
1349 if (s == NULL) /* invalid, though! */
1351 /* make a copy to store the parsed string */
1352 if (!(dup = ast_strdup(s)))
1356 /* scan the original string copying into cur when needed */
1359 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1362 if (*s == '"' && !escaped) {
1364 if (quoted && whitespace) {
1365 /* start a quoted string from previous whitespace: new argument */
1369 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1370 /* If we are not already in whitespace, and not in a quoted string or
1371 processing an escape sequence, and just entered whitespace, then
1372 finalize the previous argument and remember that we are in whitespace
1378 } else if (*s == '\\' && !escaped) {
1382 /* we leave whitespace, and are not quoted. So it's a new argument */
1390 /* Null terminate */
1392 /* XXX put a NULL in the last argument, because some functions that take
1393 * the array may want a null-terminated array.
1394 * argc still reflects the number of non-NULL entries.
1398 *trailingwhitespace = whitespace;
1402 /*! \brief Return the number of unique matches for the generator */
1403 int ast_cli_generatornummatches(const char *text, const char *word)
1405 int matches = 0, i = 0;
1406 char *buf = NULL, *oldbuf = NULL;
1408 while ((buf = ast_cli_generator(text, word, i++))) {
1409 if (!oldbuf || strcmp(buf,oldbuf))
1420 char **ast_cli_completion_matches(const char *text, const char *word)
1422 char **match_list = NULL, *retstr, *prevstr;
1423 size_t match_list_len, max_equal, which, i;
1426 /* leave entry 0 free for the longest common substring */
1428 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1429 if (matches + 1 >= match_list_len) {
1430 match_list_len <<= 1;
1431 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1434 match_list[++matches] = retstr;
1438 return match_list; /* NULL */
1440 /* Find the longest substring that is common to all results
1441 * (it is a candidate for completion), and store a copy in entry 0.
1443 prevstr = match_list[1];
1444 max_equal = strlen(prevstr);
1445 for (which = 2; which <= matches; which++) {
1446 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1451 if (!(retstr = ast_malloc(max_equal + 1)))
1454 ast_copy_string(retstr, match_list[1], max_equal + 1);
1455 match_list[0] = retstr;
1457 /* ensure that the array is NULL terminated */
1458 if (matches + 1 >= match_list_len) {
1459 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1462 match_list[matches + 1] = NULL;
1467 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1469 char *argv[AST_MAX_ARGS];
1470 struct ast_cli_entry *e;
1471 struct cli_iterator i = { NULL, NULL };
1472 int x = 0, argindex, matchlen;
1475 char matchstr[80] = "";
1477 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1479 if (!dup) /* error */
1481 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1482 /* rebuild the command, ignore tws */
1483 ast_join(matchstr, sizeof(matchstr)-1, argv);
1484 matchlen = strlen(matchstr);
1486 strcat(matchstr, " "); /* XXX */
1491 AST_LIST_LOCK(&helpers);
1492 while( !ret && (e = cli_next(&i)) ) {
1493 int lc = strlen(e->_full_cmd);
1494 if (e->_full_cmd[0] != '_' && lc > 0 && matchlen <= lc &&
1495 !strncasecmp(matchstr, e->_full_cmd, matchlen)) {
1496 /* Found initial part, return a copy of the next word... */
1497 if (e->cmda[argindex] && ++matchnum > state)
1498 ret = strdup(e->cmda[argindex]); /* we need a malloced string */
1499 } else if (e->generator && !strncasecmp(matchstr, e->_full_cmd, lc) && matchstr[lc] < 33) {
1500 /* We have a command in its entirity within us -- theoretically only one
1501 command can have this occur */
1502 ret = e->generator(matchstr, word, argindex, state);
1506 AST_LIST_UNLOCK(&helpers);
1511 char *ast_cli_generator(const char *text, const char *word, int state)
1513 return __ast_cli_generator(text, word, state, 1);
1516 int ast_cli_command(int fd, const char *s)
1518 char *argv[AST_MAX_ARGS];
1519 struct ast_cli_entry *e;
1524 if (!(dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws)))
1527 /* We need at least one entry, or ignore */
1529 AST_LIST_LOCK(&helpers);
1530 e = find_cli(argv, 0);
1533 AST_LIST_UNLOCK(&helpers);
1535 switch(e->handler(fd, x, argv)) {
1536 case RESULT_SHOWUSAGE:
1538 ast_cli(fd, "%s", e->usage);
1540 ast_cli(fd, "Invalid usage, but no usage information available.\n");
1543 AST_LIST_LOCK(&helpers);
1544 if (e->deprecated == 1) {
1545 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);
1548 AST_LIST_UNLOCK(&helpers);
1552 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1554 ast_atomic_fetchadd_int(&e->inuse, -1);