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: module load <module name>\n"
80 " Loads the specified module into Asterisk.\n";
82 static char unload_help[] =
83 "Usage: module 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: channel list [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: module 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 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 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 nodebug\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 list 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[2])) {
146 ast_cli(fd, "Unable to load module %s\n", argv[2]);
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=2;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 < 3) || (argc > 4))
182 return RESULT_SHOWUSAGE;
184 if (!strcasecmp(argv[2], "atleast"))
189 return RESULT_SHOWUSAGE;
191 option_verbose = atoi(argv[2]);
194 return RESULT_SHOWUSAGE;
196 newlevel = atoi(argv[3]);
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 < 3) || (argc > 5))
220 return RESULT_SHOWUSAGE;
222 if (!strcasecmp(argv[2], "atleast"))
227 return RESULT_SHOWUSAGE;
229 if (sscanf(argv[2], "%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;
242 return RESULT_SHOWUSAGE;
244 if (sscanf(argv[3], "%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=2;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: module list [like keyword]\n"
345 " Shows Asterisk modules currently in use, and usage statistics.\n";
347 static char uptime_help[] =
348 "Usage: 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 == 3 && !strcasecmp(argv[2],"seconds"));
410 if (argc != 2 && !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 static int handle_modlist(int fd, int argc, char *argv[])
423 return RESULT_SHOWUSAGE;
424 else if (argc >= 4) {
425 if (strcmp(argv[2],"like"))
426 return RESULT_SHOWUSAGE;
430 ast_mutex_lock(&climodentrylock);
431 climodentryfd = fd; /* global, protected by climodentrylock */
432 ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
433 ast_cli(fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
435 ast_mutex_unlock(&climodentrylock);
436 return RESULT_SUCCESS;
438 #undef MODLIST_FORMAT
439 #undef MODLIST_FORMAT2
441 static int handle_chanlist(int fd, int argc, char *argv[])
443 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
444 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
445 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s\n"
446 #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"
447 #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"
449 struct ast_channel *c = NULL;
450 char durbuf[10] = "-";
454 int durh, durm, durs;
455 int numchans = 0, concise = 0, verbose = 0;
457 concise = (argc == 3 && (!strcasecmp(argv[2],"concise")));
458 verbose = (argc == 3 && (!strcasecmp(argv[2],"verbose")));
460 if (argc < 2 || argc > 3 || (argc == 3 && !concise && !verbose))
461 return RESULT_SHOWUSAGE;
463 if (!concise && !verbose)
464 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
466 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
467 "CallerID", "Duration", "Accountcode", "BridgedTo");
469 while ((c = ast_channel_walk_locked(c)) != NULL) {
470 struct ast_channel *bc = ast_bridged_channel(c);
471 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
472 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
474 durh = duration / 3600;
475 durm = (duration % 3600) / 60;
476 durs = duration % 60;
477 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
479 snprintf(durbuf, sizeof(durbuf), "%d", duration);
485 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
486 c->appl ? c->appl : "(None)",
487 S_OR(c->data, ""), /* XXX different from verbose ? */
488 S_OR(c->cid.cid_num, ""),
489 S_OR(c->accountcode, ""),
492 bc ? bc->name : "(None)");
493 } else if (verbose) {
494 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
495 c->appl ? c->appl : "(None)",
496 c->data ? S_OR(c->data, "(Empty)" ): "(None)",
497 S_OR(c->cid.cid_num, ""),
499 S_OR(c->accountcode, ""),
500 bc ? bc->name : "(None)");
502 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
503 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
505 strcpy(locbuf, "(None)");
507 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, c->data ? c->data : "");
509 strcpy(appdata, "(None)");
510 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
513 ast_channel_unlock(c);
516 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
518 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
519 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
520 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
522 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
524 return RESULT_SUCCESS;
527 #undef FORMAT_STRING2
528 #undef CONCISE_FORMAT_STRING
529 #undef VERBOSE_FORMAT_STRING
530 #undef VERBOSE_FORMAT_STRING2
533 static char showchan_help[] =
534 "Usage: channel show <channel>\n"
535 " Shows lots of information about the specified channel.\n";
537 static char debugchan_help[] =
538 "Usage: channel debug <channel>\n"
539 " Enables debugging on a specific channel.\n";
541 static char nodebugchan_help[] =
542 "Usage: channel nodebug <channel>\n"
543 " Disables debugging on a specific channel.\n";
545 static char commandcomplete_help[] =
546 "Usage: _command complete \"<line>\" text state\n"
547 " This function is used internally to help with command completion and should.\n"
548 " never be called by the user directly.\n";
550 static char commandnummatches_help[] =
551 "Usage: _command nummatches \"<line>\" text \n"
552 " This function is used internally to help with command completion and should.\n"
553 " never be called by the user directly.\n";
555 static char commandmatchesarray_help[] =
556 "Usage: _command matchesarray \"<line>\" text \n"
557 " This function is used internally to help with command completion and should.\n"
558 " never be called by the user directly.\n";
560 static int handle_softhangup(int fd, int argc, char *argv[])
562 struct ast_channel *c=NULL;
564 return RESULT_SHOWUSAGE;
565 c = ast_get_channel_by_name_locked(argv[2]);
567 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
568 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
569 ast_channel_unlock(c);
571 ast_cli(fd, "%s is not a known channel\n", argv[2]);
572 return RESULT_SUCCESS;
575 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
577 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
586 return RESULT_SHOWUSAGE;
587 if (!(buf = ast_malloc(buflen)))
588 return RESULT_FAILURE;
590 matches = ast_cli_completion_matches(argv[2], argv[3]);
592 for (x=0; matches[x]; x++) {
593 matchlen = strlen(matches[x]) + 1;
594 if (len + matchlen >= buflen) {
595 buflen += matchlen * 3;
597 if (!(buf = ast_realloc(obuf, buflen)))
598 /* Memory allocation failure... Just free old buffer and be done */
602 len += sprintf( buf + len, "%s ", matches[x]);
610 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
613 ast_cli(fd, "NULL\n");
615 return RESULT_SUCCESS;
620 static int handle_commandnummatches(int fd, int argc, char *argv[])
625 return RESULT_SHOWUSAGE;
627 matches = ast_cli_generatornummatches(argv[2], argv[3]);
629 ast_cli(fd, "%d", matches);
631 return RESULT_SUCCESS;
634 static int handle_commandcomplete(int fd, int argc, char *argv[])
639 return RESULT_SHOWUSAGE;
640 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
645 ast_cli(fd, "NULL\n");
646 return RESULT_SUCCESS;
649 /* XXX todo: merge next two functions!!! */
650 static int handle_debugchan(int fd, int argc, char *argv[])
652 struct ast_channel *c=NULL;
655 /* 'debug channel {all|chan_id}' */
657 return RESULT_SHOWUSAGE;
659 is_all = !strcasecmp("all", argv[2]);
661 global_fin |= DEBUGCHAN_FLAG;
662 global_fout |= DEBUGCHAN_FLAG;
663 c = ast_channel_walk_locked(NULL);
665 c = ast_get_channel_by_name_locked(argv[2]);
667 ast_cli(fd, "No such channel %s\n", argv[2]);
670 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
671 c->fin |= DEBUGCHAN_FLAG;
672 c->fout |= DEBUGCHAN_FLAG;
673 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
675 ast_channel_unlock(c);
678 c = ast_channel_walk_locked(c);
680 ast_cli(fd, "Debugging on new channels is enabled\n");
681 return RESULT_SUCCESS;
684 static int handle_nodebugchan(int fd, int argc, char *argv[])
686 struct ast_channel *c=NULL;
688 /* 'no debug channel {all|chan_id}' */
690 return RESULT_SHOWUSAGE;
691 is_all = !strcasecmp("all", argv[2]);
693 global_fin &= ~DEBUGCHAN_FLAG;
694 global_fout &= ~DEBUGCHAN_FLAG;
695 c = ast_channel_walk_locked(NULL);
697 c = ast_get_channel_by_name_locked(argv[2]);
699 ast_cli(fd, "No such channel %s\n", argv[2]);
702 if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
703 c->fin &= ~DEBUGCHAN_FLAG;
704 c->fout &= ~DEBUGCHAN_FLAG;
705 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
707 ast_channel_unlock(c);
710 c = ast_channel_walk_locked(c);
712 ast_cli(fd, "Debugging on new channels is disabled\n");
713 return RESULT_SUCCESS;
716 static int handle_showchan(int fd, int argc, char *argv[])
718 struct ast_channel *c=NULL;
722 char nf[256], wf[256], rf[256];
723 long elapsed_seconds=0;
724 int hour=0, min=0, sec=0;
727 return RESULT_SHOWUSAGE;
729 c = ast_get_channel_by_name_locked(argv[2]);
731 ast_cli(fd, "%s is not a known channel\n", argv[2]);
732 return RESULT_SUCCESS;
735 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
736 hour = elapsed_seconds / 3600;
737 min = (elapsed_seconds % 3600) / 60;
738 sec = elapsed_seconds % 60;
739 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
741 strcpy(cdrtime, "N/A");
748 " Caller ID Name: %s\n"
752 " NativeFormats: %s\n"
755 " WriteTranscode: %s\n"
756 " ReadTranscode: %s\n"
757 "1st File Descriptor: %d\n"
759 " Frames out: %d%s\n"
760 " Time to Hangup: %ld\n"
761 " Elapsed Time: %s\n"
762 " Direct Bridge: %s\n"
763 "Indirect Bridge: %s\n"
768 " Call Group: %llu\n"
769 " Pickup Group: %llu\n"
772 " Blocking in: %s\n",
773 c->name, c->tech->type, c->uniqueid,
774 S_OR(c->cid.cid_num, "(N/A)"),
775 S_OR(c->cid.cid_name, "(N/A)"),
776 S_OR(c->cid.cid_dnid, "(N/A)"), ast_state2str(c->_state), c->_state, c->rings,
777 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
778 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
779 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
780 c->writetrans ? "Yes" : "No",
781 c->readtrans ? "Yes" : "No",
783 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
784 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
785 (long)c->whentohangup,
786 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
787 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
788 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
789 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
791 if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
792 ast_cli(fd," Variables:\n%s\n",buf);
793 if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
794 ast_cli(fd," CDR Variables:\n%s\n",buf);
796 ast_channel_unlock(c);
797 return RESULT_SUCCESS;
801 * helper function to generate CLI matches from a fixed set of values.
802 * A NULL word is acceptable.
804 char *ast_cli_complete(const char *word, char *const choices[], int state)
806 int i, which = 0, len;
807 len = ast_strlen_zero(word) ? 0 : strlen(word);
809 for (i = 0; choices[i]; i++) {
810 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
811 return ast_strdup(choices[i]);
816 static char *complete_show_channels(const char *line, const char *word, int pos, int state)
818 static char *choices[] = { "concise", "verbose", NULL };
820 return (pos != 2) ? NULL : ast_cli_complete(word, choices, state);
823 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
825 struct ast_channel *c = NULL;
828 char notfound = '\0';
829 char *ret = ¬found; /* so NULL can break the loop */
834 wordlen = strlen(word);
836 while (ret == ¬found && (c = ast_channel_walk_locked(c))) {
837 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
838 ret = ast_strdup(c->name);
839 ast_channel_unlock(c);
841 return ret == ¬found ? NULL : ret;
844 static char *complete_ch_3(const char *line, const char *word, int pos, int state)
846 return ast_complete_channels(line, word, pos, state, 2);
849 static char *complete_mod_3_nr(const char *line, const char *word, int pos, int state)
851 return ast_module_helper(line, word, pos, state, 2, 0);
854 static char *complete_mod_3(const char *line, const char *word, int pos, int state)
856 return ast_module_helper(line, word, pos, state, 2, 1);
859 static char *complete_mod_4(const char *line, const char *word, int pos, int state)
861 return ast_module_helper(line, word, pos, state, 3, 0);
864 static char *complete_fn(const char *line, const char *word, int pos, int state)
873 ast_copy_string(filename, word, sizeof(filename));
875 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
877 c = filename_completion_function(filename, state);
879 if (c && word[0] != '/')
880 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
882 return c ? strdup(c) : c;
885 static int group_show_channels(int fd, int argc, char *argv[])
887 #define FORMAT_STRING "%-25s %-20s %-20s\n"
889 struct ast_channel *c = NULL;
891 struct ast_var_t *current;
892 struct varshead *headp;
896 if (argc < 3 || argc > 4)
897 return RESULT_SHOWUSAGE;
900 if (regcomp(®exbuf, argv[3], REG_EXTENDED | REG_NOSUB))
901 return RESULT_SHOWUSAGE;
905 ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
906 while ( (c = ast_channel_walk_locked(c)) != NULL) {
908 AST_LIST_TRAVERSE(headp,current,entries) {
909 if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
910 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
911 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
912 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
915 } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
916 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
917 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
923 ast_channel_unlock(c);
929 ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
930 return RESULT_SUCCESS;
934 static int handle_help(int fd, int argc, char *argv[]);
936 static char * complete_help(const char *text, const char *word, int pos, int state)
938 /* skip first 4 or 5 chars, "help "*/
939 int l = strlen(text);
944 /* XXX watch out, should stop to the non-generator parts */
945 return __ast_cli_generator(text, word, state, 0);
948 /* XXX Nothing in this array can currently be deprecated...
949 You have to change the way find_cli works in order to remove this array
950 I recommend doing this eventually...
952 static struct ast_cli_entry builtins[] = {
953 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
954 { { "_command", "complete", NULL },
955 handle_commandcomplete, "Command complete",
956 commandcomplete_help },
958 { { "_command", "nummatches", NULL },
959 handle_commandnummatches, "Returns number of command matches",
960 commandnummatches_help },
962 { { "_command", "matchesarray", NULL },
963 handle_commandmatchesarray, "Returns command matches array",
964 commandmatchesarray_help },
966 { { NULL }, NULL, NULL, NULL }
969 static struct ast_cli_entry cli_cli[] = {
970 { { "channel", "list", NULL },
971 handle_chanlist, "Display information on channels",
972 chanlist_help, complete_show_channels },
974 { { "channel", "show", NULL },
975 handle_showchan, "Display information on a specific channel",
976 showchan_help, complete_ch_3 },
978 { { "channel", "debug", NULL },
979 handle_debugchan, "Enable debugging on a channel",
980 debugchan_help, complete_ch_3 },
982 { { "channel", "nodebug", NULL },
983 handle_nodebugchan, "Disable debugging on a channel",
984 nodebugchan_help, complete_ch_3 },
986 { { "core", "debug", NULL },
987 handle_debug, "Set level of debug chattiness",
990 { { "core", "nodebug", NULL },
991 handle_nodebug, "Turns off debug chattiness",
994 { { "core", "verbose", NULL },
995 handle_verbose, "Set level of verboseness",
998 { { "group", "list", "channels", NULL },
999 group_show_channels, "Display active channels with group(s)",
1000 group_show_channels_help },
1003 handle_help, "Display help list, or specific help on a command",
1004 help_help, complete_help },
1006 { { "logger", "mute", NULL },
1007 handle_logger_mute, "Toggle logging output to a console",
1010 { { "module", "list", NULL },
1011 handle_modlist, "List modules and info",
1014 { { "module", "list", "like", NULL },
1015 handle_modlist, "List modules and info",
1016 modlist_help, complete_mod_4 },
1018 { { "module", "load", NULL },
1019 handle_load, "Load a module by name",
1020 load_help, complete_fn },
1022 { { "module", "reload", NULL },
1023 handle_reload, "Reload configuration",
1024 reload_help, complete_mod_3 },
1026 { { "module", "unload", NULL },
1027 handle_unload, "Unload a module by name",
1028 unload_help, complete_mod_3_nr },
1030 { { "show", "uptime", NULL },
1031 handle_showuptime, "Show uptime information",
1034 { { "soft", "hangup", NULL },
1035 handle_softhangup, "Request a hangup on a given channel",
1036 softhangup_help, complete_ch_3 },
1039 /*! \brief initialize the _full_cmd string in * each of the builtins. */
1040 void ast_builtins_init(void)
1042 struct ast_cli_entry *e;
1044 for (e = builtins; e->cmda[0] != NULL; e++) {
1046 ast_join(buf, sizeof(buf), e->cmda);
1047 e->_full_cmd = strdup(buf);
1049 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
1052 ast_cli_register_multiple(cli_cli, sizeof(cli_cli) / sizeof(struct ast_cli_entry));
1056 * We have two sets of commands: builtins are stored in a
1057 * NULL-terminated array of ast_cli_entry, whereas external
1058 * commands are in a list.
1059 * When navigating, we need to keep two pointers and get
1060 * the next one in lexicographic order. For the purpose,
1061 * we use a structure.
1064 struct cli_iterator {
1065 struct ast_cli_entry *builtins;
1066 struct ast_cli_entry *helpers;
1069 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
1071 struct ast_cli_entry *e;
1073 if (i->builtins == NULL && i->helpers == NULL) {
1075 i->builtins = builtins;
1076 i->helpers = AST_LIST_FIRST(&helpers);
1078 e = i->builtins; /* temporary */
1079 if (!e->cmda[0] || (i->helpers &&
1080 strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
1084 i->helpers = AST_LIST_NEXT(e, list);
1085 } else { /* use builtin. e is already set */
1086 (i->builtins)++; /* move to next */
1092 * \brief locate a cli command in the 'helpers' list (which must be locked).
1093 * exact has 3 values:
1094 * 0 returns if the search key is equal or longer than the entry.
1095 * -1 true if the mismatch is on the last word XXX not true!
1096 * 1 true only on complete, exact match.
1098 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1100 int matchlen = -1; /* length of longest match so far */
1101 struct ast_cli_entry *cand = NULL, *e=NULL;
1102 struct cli_iterator i = { NULL, NULL};
1104 while( (e = cli_next(&i)) ) {
1106 for (y = 0 ; cmds[y] && e->cmda[y]; y++) {
1107 if (strcasecmp(e->cmda[y], cmds[y]))
1110 if (e->cmda[y] == NULL) { /* no more words in candidate */
1111 if (cmds[y] == NULL) /* this is an exact match, cannot do better */
1113 /* here the search key is longer than the candidate */
1114 if (match_type != 0) /* but we look for almost exact match... */
1115 continue; /* so we skip this one. */
1116 /* otherwise we like it (case 0) */
1117 } else { /* still words in candidate */
1118 if (cmds[y] == NULL) /* search key is shorter, not good */
1120 /* if we get here, both words exist but there is a mismatch */
1121 if (match_type == 0) /* not the one we look for */
1123 if (match_type == 1) /* not the one we look for */
1125 if (cmds[y+1] != NULL || e->cmda[y+1] != NULL) /* not the one we look for */
1127 /* we are in case match_type == -1 and mismatch on last word */
1129 if (cand == NULL || y > matchlen) /* remember the candidate */
1132 return e ? e : cand;
1135 static char *find_best(char *argv[])
1137 static char cmdline[80];
1139 /* See how close we get, then print the candidate */
1140 char *myargv[AST_MAX_CMD_LEN];
1141 for (x=0;x<AST_MAX_CMD_LEN;x++)
1143 AST_LIST_LOCK(&helpers);
1144 for (x=0;argv[x];x++) {
1145 myargv[x] = argv[x];
1146 if (!find_cli(myargv, -1))
1149 AST_LIST_UNLOCK(&helpers);
1150 ast_join(cmdline, sizeof(cmdline), myargv);
1154 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1156 if (e->deprecate_cmd) {
1157 __ast_cli_unregister(e->deprecate_cmd, e);
1160 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1162 AST_LIST_LOCK(&helpers);
1163 AST_LIST_REMOVE(&helpers, e, list);
1164 AST_LIST_UNLOCK(&helpers);
1169 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1171 struct ast_cli_entry *cur;
1175 ast_join(fulle, sizeof(fulle), e->cmda);
1176 AST_LIST_LOCK(&helpers);
1178 if (find_cli(e->cmda, 1)) {
1179 AST_LIST_UNLOCK(&helpers);
1180 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1183 e->_full_cmd = ast_strdup(fulle);
1189 e->summary = ed->summary;
1190 e->usage = ed->usage;
1191 /* XXX If command A deprecates command B, and command B deprecates command C...
1192 Do we want to show command A or command B when telling the user to use new syntax?
1193 This currently would show command A.
1194 To show command B, you just need to always use ed->_full_cmd.
1196 e->_deprecated_by = S_OR(ed->_deprecated_by, ed->_full_cmd);
1202 AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1203 int len = strlen(cur->_full_cmd);
1206 if (strncasecmp(fulle, cur->_full_cmd, len) < 0) {
1207 AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list);
1211 AST_LIST_TRAVERSE_SAFE_END;
1214 AST_LIST_INSERT_TAIL(&helpers, e, list);
1215 ret = 0; /* success */
1218 AST_LIST_UNLOCK(&helpers);
1220 if (e->deprecate_cmd) {
1221 /* This command deprecates another command. Register that one also. */
1222 __ast_cli_register(e->deprecate_cmd, e);
1228 /* wrapper function, so we can unregister deprecated commands recursively */
1229 int ast_cli_unregister(struct ast_cli_entry *e)
1231 return __ast_cli_unregister(e, NULL);
1234 /* wrapper function, so we can register deprecated commands recursively */
1235 int ast_cli_register(struct ast_cli_entry *e)
1237 return __ast_cli_register(e, NULL);
1241 * register/unregister an array of entries.
1243 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1247 for (i = 0; i < len; i++)
1248 ast_cli_register(e + i);
1251 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1255 for (i = 0; i < len; i++)
1256 ast_cli_unregister(e + i);
1260 /*! \brief helper for help_workhorse and final part of
1261 * handle_help. if locked = 0 it's just help_workhorse,
1262 * otherwise assume the list is already locked and print
1263 * an error message if not found.
1265 static int help1(int fd, char *match[], int locked)
1267 char matchstr[80] = "";
1268 struct ast_cli_entry *e;
1271 struct cli_iterator i = { NULL, NULL};
1274 ast_join(matchstr, sizeof(matchstr), match);
1275 len = strlen(matchstr);
1278 AST_LIST_LOCK(&helpers);
1279 while ( (e = cli_next(&i)) ) {
1280 /* Hide commands that start with '_' */
1281 if (e->_full_cmd[0] == '_')
1283 /* Hide commands that are marked as deprecated. */
1286 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1288 ast_cli(fd, "%25.25s %s\n", e->_full_cmd, e->summary);
1291 AST_LIST_UNLOCK(&helpers);
1292 if (!locked && !found && matchstr[0])
1293 ast_cli(fd, "No such command '%s'.\n", matchstr);
1297 static int help_workhorse(int fd, char *match[])
1299 return help1(fd, match, 0 /* do not print errors */);
1302 static int handle_help(int fd, int argc, char *argv[])
1305 struct ast_cli_entry *e;
1308 return RESULT_SHOWUSAGE;
1310 return help_workhorse(fd, NULL);
1312 AST_LIST_LOCK(&helpers);
1313 e = find_cli(argv + 1, 1); /* try exact match first */
1315 return help1(fd, argv + 1, 1 /* locked */);
1317 ast_cli(fd, "%s", e->usage);
1319 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1320 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1322 AST_LIST_UNLOCK(&helpers);
1323 return RESULT_SUCCESS;
1326 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1334 *trailingwhitespace = 0;
1335 if (s == NULL) /* invalid, though! */
1337 /* make a copy to store the parsed string */
1338 if (!(dup = ast_strdup(s)))
1342 /* scan the original string copying into cur when needed */
1345 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1348 if (*s == '"' && !escaped) {
1350 if (quoted && whitespace) {
1351 /* start a quoted string from previous whitespace: new argument */
1355 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1356 /* If we are not already in whitespace, and not in a quoted string or
1357 processing an escape sequence, and just entered whitespace, then
1358 finalize the previous argument and remember that we are in whitespace
1364 } else if (*s == '\\' && !escaped) {
1368 /* we leave whitespace, and are not quoted. So it's a new argument */
1376 /* Null terminate */
1378 /* XXX put a NULL in the last argument, because some functions that take
1379 * the array may want a null-terminated array.
1380 * argc still reflects the number of non-NULL entries.
1384 *trailingwhitespace = whitespace;
1388 /*! \brief Return the number of unique matches for the generator */
1389 int ast_cli_generatornummatches(const char *text, const char *word)
1391 int matches = 0, i = 0;
1392 char *buf = NULL, *oldbuf = NULL;
1394 while ((buf = ast_cli_generator(text, word, i++))) {
1395 if (!oldbuf || strcmp(buf,oldbuf))
1406 char **ast_cli_completion_matches(const char *text, const char *word)
1408 char **match_list = NULL, *retstr, *prevstr;
1409 size_t match_list_len, max_equal, which, i;
1412 /* leave entry 0 free for the longest common substring */
1414 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1415 if (matches + 1 >= match_list_len) {
1416 match_list_len <<= 1;
1417 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1420 match_list[++matches] = retstr;
1424 return match_list; /* NULL */
1426 /* Find the longest substring that is common to all results
1427 * (it is a candidate for completion), and store a copy in entry 0.
1429 prevstr = match_list[1];
1430 max_equal = strlen(prevstr);
1431 for (which = 2; which <= matches; which++) {
1432 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1437 if (!(retstr = ast_malloc(max_equal + 1)))
1440 ast_copy_string(retstr, match_list[1], max_equal + 1);
1441 match_list[0] = retstr;
1443 /* ensure that the array is NULL terminated */
1444 if (matches + 1 >= match_list_len) {
1445 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1448 match_list[matches + 1] = NULL;
1453 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1455 char *argv[AST_MAX_ARGS];
1456 struct ast_cli_entry *e;
1457 struct cli_iterator i = { NULL, NULL };
1458 int x = 0, argindex, matchlen;
1461 char matchstr[80] = "";
1463 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1465 if (!dup) /* error */
1467 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1468 /* rebuild the command, ignore tws */
1469 ast_join(matchstr, sizeof(matchstr)-1, argv);
1470 matchlen = strlen(matchstr);
1472 strcat(matchstr, " "); /* XXX */
1477 AST_LIST_LOCK(&helpers);
1478 while( !ret && (e = cli_next(&i)) ) {
1479 int lc = strlen(e->_full_cmd);
1480 if (e->_full_cmd[0] != '_' && lc > 0 && matchlen <= lc &&
1481 !strncasecmp(matchstr, e->_full_cmd, matchlen)) {
1482 /* Found initial part, return a copy of the next word... */
1483 if (e->cmda[argindex] && ++matchnum > state)
1484 ret = strdup(e->cmda[argindex]); /* we need a malloced string */
1485 } else if (e->generator && !strncasecmp(matchstr, e->_full_cmd, lc) && matchstr[lc] < 33) {
1486 /* We have a command in its entirity within us -- theoretically only one
1487 command can have this occur */
1488 ret = e->generator(matchstr, word, argindex, state);
1492 AST_LIST_UNLOCK(&helpers);
1497 char *ast_cli_generator(const char *text, const char *word, int state)
1499 return __ast_cli_generator(text, word, state, 1);
1502 int ast_cli_command(int fd, const char *s)
1504 char *argv[AST_MAX_ARGS];
1505 struct ast_cli_entry *e;
1510 if (!(dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws)))
1513 /* We need at least one entry, or ignore */
1515 AST_LIST_LOCK(&helpers);
1516 e = find_cli(argv, 0);
1519 AST_LIST_UNLOCK(&helpers);
1521 switch(e->handler(fd, x, argv)) {
1522 case RESULT_SHOWUSAGE:
1524 ast_cli(fd, "%s", e->usage);
1526 ast_cli(fd, "Invalid usage, but no usage information available.\n");
1529 AST_LIST_LOCK(&helpers);
1530 if (e->deprecated == 1) {
1531 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);
1534 AST_LIST_UNLOCK(&helpers);
1538 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1540 ast_atomic_fetchadd_int(&e->inuse, -1);