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, ast_cli_buf_init);
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;
180 option_verbose = atoi(argv[2]);
182 return RESULT_SHOWUSAGE;
184 if (oldval > 0 && option_verbose == 0)
185 ast_cli(fd, "Verbosity is now OFF\n");
186 else if (option_verbose > 0) {
187 if (oldval == option_verbose)
188 ast_cli(fd, "Verbosity is at least %d\n", option_verbose);
190 ast_cli(fd, "Verbosity was %d and is now %d\n", oldval, option_verbose);
193 return RESULT_SUCCESS;
196 static int handle_debug(int fd, int argc, char *argv[])
198 int oldval = option_debug;
200 char *filename = '\0';
202 if ((argc < 3) || (argc > 4))
203 return RESULT_SHOWUSAGE;
205 if (sscanf(argv[2], "%d", &newlevel) != 1)
206 return RESULT_SHOWUSAGE;
208 option_debug = newlevel;
212 ast_copy_string(debug_filename, filename, sizeof(debug_filename));
214 debug_filename[0] = '\0';
217 if (oldval > 0 && option_debug == 0)
218 ast_cli(fd, "Core debug is now OFF\n");
219 else if (option_debug > 0) {
221 if (oldval == option_debug)
222 ast_cli(fd, "Core debug is at least %d, file '%s'\n", option_debug, filename);
224 ast_cli(fd, "Core debug was %d and is now %d, file '%s'\n", oldval, option_debug, filename);
226 if (oldval == option_debug)
227 ast_cli(fd, "Core debug is at least %d\n", option_debug);
229 ast_cli(fd, "Core debug was %d and is now %d\n", oldval, option_debug);
233 return RESULT_SUCCESS;
236 static int handle_nodebug(int fd, int argc, char *argv[])
238 int oldval = option_debug;
240 return RESULT_SHOWUSAGE;
243 debug_filename[0] = '\0';
246 ast_cli(fd, "Core debug is now OFF\n");
247 return RESULT_SUCCESS;
250 static int handle_logger_mute(int fd, int argc, char *argv[])
253 return RESULT_SHOWUSAGE;
254 ast_console_toggle_mute(fd);
255 return RESULT_SUCCESS;
258 static int handle_unload(int fd, int argc, char *argv[])
261 int force=AST_FORCE_SOFT;
263 return RESULT_SHOWUSAGE;
264 for (x=2;x<argc;x++) {
265 if (argv[x][0] == '-') {
268 force = AST_FORCE_FIRM;
271 force = AST_FORCE_HARD;
274 return RESULT_SHOWUSAGE;
276 } else if (x != argc - 1)
277 return RESULT_SHOWUSAGE;
278 else if (ast_unload_resource(argv[x], force)) {
279 ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
280 return RESULT_FAILURE;
283 return RESULT_SUCCESS;
286 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
287 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
289 AST_MUTEX_DEFINE_STATIC(climodentrylock);
290 static int climodentryfd = -1;
292 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
294 /* Comparing the like with the module */
295 if (strcasestr(module, like) ) {
296 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
302 static char modlist_help[] =
303 "Usage: module list [like keyword]\n"
304 " Shows Asterisk modules currently in use, and usage statistics.\n";
306 static char uptime_help[] =
307 "Usage: show uptime [seconds]\n"
308 " Shows Asterisk uptime information.\n"
309 " The seconds word returns the uptime in seconds only.\n";
311 static void print_uptimestr(int fd, time_t timeval, const char *prefix, int printsec)
313 int x; /* the main part - years, weeks, etc. */
314 char timestr[256]="", *s = timestr;
315 size_t maxbytes = sizeof(timestr);
318 #define MINUTE (SECOND*60)
319 #define HOUR (MINUTE*60)
320 #define DAY (HOUR*24)
322 #define YEAR (DAY*365)
323 #define ESS(x) ((x == 1) ? "" : "s") /* plural suffix */
324 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
325 if (timeval < 0) /* invalid, nothing to show */
327 if (printsec) { /* plain seconds output */
328 ast_build_string(&s, &maxbytes, "%lu", (u_long)timeval);
329 timeval = 0; /* bypass the other cases */
331 if (timeval > YEAR) {
332 x = (timeval / YEAR);
333 timeval -= (x * YEAR);
334 ast_build_string(&s, &maxbytes, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval));
336 if (timeval > WEEK) {
337 x = (timeval / WEEK);
338 timeval -= (x * WEEK);
339 ast_build_string(&s, &maxbytes, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval));
343 timeval -= (x * DAY);
344 ast_build_string(&s, &maxbytes, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval));
346 if (timeval > HOUR) {
347 x = (timeval / HOUR);
348 timeval -= (x * HOUR);
349 ast_build_string(&s, &maxbytes, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval));
351 if (timeval > MINUTE) {
352 x = (timeval / MINUTE);
353 timeval -= (x * MINUTE);
354 ast_build_string(&s, &maxbytes, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval));
358 ast_build_string(&s, &maxbytes, "%d second%s ", x, ESS(x));
359 if (timestr[0] != '\0')
360 ast_cli(fd, "%s: %s\n", prefix, timestr);
363 static int handle_showuptime(int fd, int argc, char *argv[])
365 /* 'show uptime [seconds]' */
366 time_t curtime = time(NULL);
367 int printsec = (argc == 3 && !strcasecmp(argv[2],"seconds"));
369 if (argc != 2 && !printsec)
370 return RESULT_SHOWUSAGE;
372 print_uptimestr(fd, curtime - ast_startuptime, "System uptime", printsec);
373 if (ast_lastreloadtime)
374 print_uptimestr(fd, curtime - ast_lastreloadtime, "Last reload", printsec);
375 return RESULT_SUCCESS;
378 static int handle_modlist(int fd, int argc, char *argv[])
382 return RESULT_SHOWUSAGE;
383 else if (argc >= 4) {
384 if (strcmp(argv[2],"like"))
385 return RESULT_SHOWUSAGE;
389 ast_mutex_lock(&climodentrylock);
390 climodentryfd = fd; /* global, protected by climodentrylock */
391 ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
392 ast_cli(fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
394 ast_mutex_unlock(&climodentrylock);
395 return RESULT_SUCCESS;
397 #undef MODLIST_FORMAT
398 #undef MODLIST_FORMAT2
400 static int handle_chanlist(int fd, int argc, char *argv[])
402 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
403 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
404 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s\n"
405 #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"
406 #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"
408 struct ast_channel *c = NULL;
409 char durbuf[10] = "-";
413 int durh, durm, durs;
414 int numchans = 0, concise = 0, verbose = 0;
416 concise = (argc == 3 && (!strcasecmp(argv[2],"concise")));
417 verbose = (argc == 3 && (!strcasecmp(argv[2],"verbose")));
419 if (argc < 2 || argc > 3 || (argc == 3 && !concise && !verbose))
420 return RESULT_SHOWUSAGE;
422 if (!concise && !verbose)
423 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
425 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
426 "CallerID", "Duration", "Accountcode", "BridgedTo");
428 while ((c = ast_channel_walk_locked(c)) != NULL) {
429 struct ast_channel *bc = ast_bridged_channel(c);
430 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
431 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
433 durh = duration / 3600;
434 durm = (duration % 3600) / 60;
435 durs = duration % 60;
436 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
438 snprintf(durbuf, sizeof(durbuf), "%d", duration);
444 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
445 c->appl ? c->appl : "(None)",
446 S_OR(c->data, ""), /* XXX different from verbose ? */
447 S_OR(c->cid.cid_num, ""),
448 S_OR(c->accountcode, ""),
451 bc ? bc->name : "(None)");
452 } else if (verbose) {
453 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
454 c->appl ? c->appl : "(None)",
455 c->data ? S_OR(c->data, "(Empty)" ): "(None)",
456 S_OR(c->cid.cid_num, ""),
458 S_OR(c->accountcode, ""),
459 bc ? bc->name : "(None)");
461 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
462 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
464 strcpy(locbuf, "(None)");
466 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, c->data ? c->data : "");
468 strcpy(appdata, "(None)");
469 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
472 ast_channel_unlock(c);
475 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
477 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
478 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
479 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
481 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
483 return RESULT_SUCCESS;
486 #undef FORMAT_STRING2
487 #undef CONCISE_FORMAT_STRING
488 #undef VERBOSE_FORMAT_STRING
489 #undef VERBOSE_FORMAT_STRING2
492 static char showchan_help[] =
493 "Usage: channel show <channel>\n"
494 " Shows lots of information about the specified channel.\n";
496 static char debugchan_help[] =
497 "Usage: channel debug <channel>\n"
498 " Enables debugging on a specific channel.\n";
500 static char nodebugchan_help[] =
501 "Usage: channel nodebug <channel>\n"
502 " Disables debugging on a specific channel.\n";
504 static char commandcomplete_help[] =
505 "Usage: _command complete \"<line>\" text state\n"
506 " This function is used internally to help with command completion and should.\n"
507 " never be called by the user directly.\n";
509 static char commandnummatches_help[] =
510 "Usage: _command nummatches \"<line>\" text \n"
511 " This function is used internally to help with command completion and should.\n"
512 " never be called by the user directly.\n";
514 static char commandmatchesarray_help[] =
515 "Usage: _command matchesarray \"<line>\" text \n"
516 " This function is used internally to help with command completion and should.\n"
517 " never be called by the user directly.\n";
519 static int handle_softhangup(int fd, int argc, char *argv[])
521 struct ast_channel *c=NULL;
523 return RESULT_SHOWUSAGE;
524 c = ast_get_channel_by_name_locked(argv[2]);
526 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
527 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
528 ast_channel_unlock(c);
530 ast_cli(fd, "%s is not a known channel\n", argv[2]);
531 return RESULT_SUCCESS;
534 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
536 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
545 return RESULT_SHOWUSAGE;
546 if (!(buf = ast_malloc(buflen)))
547 return RESULT_FAILURE;
549 matches = ast_cli_completion_matches(argv[2], argv[3]);
551 for (x=0; matches[x]; x++) {
552 matchlen = strlen(matches[x]) + 1;
553 if (len + matchlen >= buflen) {
554 buflen += matchlen * 3;
556 if (!(buf = ast_realloc(obuf, buflen)))
557 /* Memory allocation failure... Just free old buffer and be done */
561 len += sprintf( buf + len, "%s ", matches[x]);
569 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
572 ast_cli(fd, "NULL\n");
574 return RESULT_SUCCESS;
579 static int handle_commandnummatches(int fd, int argc, char *argv[])
584 return RESULT_SHOWUSAGE;
586 matches = ast_cli_generatornummatches(argv[2], argv[3]);
588 ast_cli(fd, "%d", matches);
590 return RESULT_SUCCESS;
593 static int handle_commandcomplete(int fd, int argc, char *argv[])
598 return RESULT_SHOWUSAGE;
599 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
604 ast_cli(fd, "NULL\n");
605 return RESULT_SUCCESS;
608 /* XXX todo: merge next two functions!!! */
609 static int handle_debugchan(int fd, int argc, char *argv[])
611 struct ast_channel *c=NULL;
614 /* 'debug channel {all|chan_id}' */
616 return RESULT_SHOWUSAGE;
618 is_all = !strcasecmp("all", argv[2]);
620 global_fin |= DEBUGCHAN_FLAG;
621 global_fout |= DEBUGCHAN_FLAG;
622 c = ast_channel_walk_locked(NULL);
624 c = ast_get_channel_by_name_locked(argv[2]);
626 ast_cli(fd, "No such channel %s\n", argv[2]);
629 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
630 c->fin |= DEBUGCHAN_FLAG;
631 c->fout |= DEBUGCHAN_FLAG;
632 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
634 ast_channel_unlock(c);
637 c = ast_channel_walk_locked(c);
639 ast_cli(fd, "Debugging on new channels is enabled\n");
640 return RESULT_SUCCESS;
643 static int handle_nodebugchan(int fd, int argc, char *argv[])
645 struct ast_channel *c=NULL;
647 /* 'no debug channel {all|chan_id}' */
649 return RESULT_SHOWUSAGE;
650 is_all = !strcasecmp("all", argv[2]);
652 global_fin &= ~DEBUGCHAN_FLAG;
653 global_fout &= ~DEBUGCHAN_FLAG;
654 c = ast_channel_walk_locked(NULL);
656 c = ast_get_channel_by_name_locked(argv[2]);
658 ast_cli(fd, "No such channel %s\n", argv[2]);
661 if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
662 c->fin &= ~DEBUGCHAN_FLAG;
663 c->fout &= ~DEBUGCHAN_FLAG;
664 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
666 ast_channel_unlock(c);
669 c = ast_channel_walk_locked(c);
671 ast_cli(fd, "Debugging on new channels is disabled\n");
672 return RESULT_SUCCESS;
675 static int handle_showchan(int fd, int argc, char *argv[])
677 struct ast_channel *c=NULL;
681 char nf[256], wf[256], rf[256];
682 long elapsed_seconds=0;
683 int hour=0, min=0, sec=0;
686 return RESULT_SHOWUSAGE;
688 c = ast_get_channel_by_name_locked(argv[2]);
690 ast_cli(fd, "%s is not a known channel\n", argv[2]);
691 return RESULT_SUCCESS;
694 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
695 hour = elapsed_seconds / 3600;
696 min = (elapsed_seconds % 3600) / 60;
697 sec = elapsed_seconds % 60;
698 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
700 strcpy(cdrtime, "N/A");
707 " Caller ID Name: %s\n"
711 " NativeFormats: %s\n"
714 " WriteTranscode: %s\n"
715 " ReadTranscode: %s\n"
716 "1st File Descriptor: %d\n"
718 " Frames out: %d%s\n"
719 " Time to Hangup: %ld\n"
720 " Elapsed Time: %s\n"
721 " Direct Bridge: %s\n"
722 "Indirect Bridge: %s\n"
727 " Call Group: %lld\n"
728 " Pickup Group: %lld\n"
731 " Blocking in: %s\n",
732 c->name, c->tech->type, c->uniqueid,
733 S_OR(c->cid.cid_num, "(N/A)"),
734 S_OR(c->cid.cid_name, "(N/A)"),
735 S_OR(c->cid.cid_dnid, "(N/A)"), ast_state2str(c->_state), c->_state, c->rings,
736 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
737 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
738 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
739 c->writetrans ? "Yes" : "No",
740 c->readtrans ? "Yes" : "No",
742 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
743 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
744 (long)c->whentohangup,
745 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
746 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
747 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
748 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
750 if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
751 ast_cli(fd," Variables:\n%s\n",buf);
752 if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
753 ast_cli(fd," CDR Variables:\n%s\n",buf);
755 ast_channel_unlock(c);
756 return RESULT_SUCCESS;
760 * helper function to generate CLI matches from a fixed set of values.
761 * A NULL word is acceptable.
763 char *ast_cli_complete(const char *word, char *const choices[], int state)
765 int i, which = 0, len;
766 len = ast_strlen_zero(word) ? 0 : strlen(word);
768 for (i = 0; choices[i]; i++) {
769 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
770 return ast_strdup(choices[i]);
775 static char *complete_show_channels(const char *line, const char *word, int pos, int state)
777 static char *choices[] = { "concise", "verbose", NULL };
779 return (pos != 2) ? NULL : ast_cli_complete(word, choices, state);
782 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
784 struct ast_channel *c = NULL;
787 char notfound = '\0';
788 char *ret = ¬found; /* so NULL can break the loop */
793 wordlen = strlen(word);
795 while (ret == ¬found && (c = ast_channel_walk_locked(c))) {
796 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
797 ret = ast_strdup(c->name);
798 ast_channel_unlock(c);
800 return ret == ¬found ? NULL : ret;
803 static char *complete_ch_3(const char *line, const char *word, int pos, int state)
805 return ast_complete_channels(line, word, pos, state, 2);
808 static char *complete_mod_3_nr(const char *line, const char *word, int pos, int state)
810 return ast_module_helper(line, word, pos, state, 2, 0);
813 static char *complete_mod_3(const char *line, const char *word, int pos, int state)
815 return ast_module_helper(line, word, pos, state, 2, 1);
818 static char *complete_mod_4(const char *line, const char *word, int pos, int state)
820 return ast_module_helper(line, word, pos, state, 3, 0);
823 static char *complete_fn(const char *line, const char *word, int pos, int state)
832 ast_copy_string(filename, word, sizeof(filename));
834 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
836 c = filename_completion_function(filename, state);
838 if (c && word[0] != '/')
839 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
841 return c ? strdup(c) : c;
844 static int group_show_channels(int fd, int argc, char *argv[])
846 #define FORMAT_STRING "%-25s %-20s %-20s\n"
848 struct ast_channel *c = NULL;
850 struct ast_var_t *current;
851 struct varshead *headp;
855 if (argc < 3 || argc > 4)
856 return RESULT_SHOWUSAGE;
859 if (regcomp(®exbuf, argv[3], REG_EXTENDED | REG_NOSUB))
860 return RESULT_SHOWUSAGE;
864 ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
865 while ( (c = ast_channel_walk_locked(c)) != NULL) {
867 AST_LIST_TRAVERSE(headp,current,entries) {
868 if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
869 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
870 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
871 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
874 } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
875 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
876 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
882 ast_channel_unlock(c);
888 ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
889 return RESULT_SUCCESS;
893 static int handle_help(int fd, int argc, char *argv[]);
895 static char * complete_help(const char *text, const char *word, int pos, int state)
897 /* skip first 4 or 5 chars, "help "*/
898 int l = strlen(text);
903 /* XXX watch out, should stop to the non-generator parts */
904 return __ast_cli_generator(text, word, state, 0);
907 /* XXX Nothing in this array can currently be deprecated...
908 You have to change the way find_cli works in order to remove this array
909 I recommend doing this eventually...
911 static struct ast_cli_entry builtins[] = {
912 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
913 { { "_command", "complete", NULL },
914 handle_commandcomplete, "Command complete",
915 commandcomplete_help },
917 { { "_command", "nummatches", NULL },
918 handle_commandnummatches, "Returns number of command matches",
919 commandnummatches_help },
921 { { "_command", "matchesarray", NULL },
922 handle_commandmatchesarray, "Returns command matches array",
923 commandmatchesarray_help },
925 { { NULL }, NULL, NULL, NULL }
928 static struct ast_cli_entry cli_cli[] = {
929 { { "channel", "list", NULL },
930 handle_chanlist, "Display information on channels",
931 chanlist_help, complete_show_channels },
933 { { "channel", "show", NULL },
934 handle_showchan, "Display information on a specific channel",
935 showchan_help, complete_ch_3 },
937 { { "channel", "debug", NULL },
938 handle_debugchan, "Enable debugging on a channel",
939 debugchan_help, complete_ch_3 },
941 { { "channel", "nodebug", NULL },
942 handle_nodebugchan, "Disable debugging on a channel",
943 nodebugchan_help, complete_ch_3 },
945 { { "core", "debug", NULL },
946 handle_debug, "Set level of debug chattiness",
949 { { "core", "nodebug", NULL },
950 handle_nodebug, "Turns off debug chattiness",
953 { { "core", "verbose", NULL },
954 handle_verbose, "Set level of verboseness",
957 { { "group", "list", "channels", NULL },
958 group_show_channels, "Display active channels with group(s)",
959 group_show_channels_help },
962 handle_help, "Display help list, or specific help on a command",
963 help_help, complete_help },
965 { { "logger", "mute", NULL },
966 handle_logger_mute, "Toggle logging output to a console",
969 { { "module", "list", NULL },
970 handle_modlist, "List modules and info",
973 { { "module", "list", "like", NULL },
974 handle_modlist, "List modules and info",
975 modlist_help, complete_mod_4 },
977 { { "module", "load", NULL },
978 handle_load, "Load a module by name",
979 load_help, complete_fn },
981 { { "module", "reload", NULL },
982 handle_reload, "Reload configuration",
983 reload_help, complete_mod_3 },
985 { { "module", "unload", NULL },
986 handle_unload, "Unload a module by name",
987 unload_help, complete_mod_3_nr },
989 { { "show", "uptime", NULL },
990 handle_showuptime, "Show uptime information",
993 { { "soft", "hangup", NULL },
994 handle_softhangup, "Request a hangup on a given channel",
995 softhangup_help, complete_ch_3 },
998 /*! \brief initialize the _full_cmd string in * each of the builtins. */
999 void ast_builtins_init(void)
1001 struct ast_cli_entry *e;
1003 for (e = builtins; e->cmda[0] != NULL; e++) {
1005 ast_join(buf, sizeof(buf), e->cmda);
1006 e->_full_cmd = strdup(buf);
1008 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
1011 ast_cli_register_multiple(cli_cli, sizeof(cli_cli) / sizeof(struct ast_cli_entry));
1015 * We have two sets of commands: builtins are stored in a
1016 * NULL-terminated array of ast_cli_entry, whereas external
1017 * commands are in a list.
1018 * When navigating, we need to keep two pointers and get
1019 * the next one in lexicographic order. For the purpose,
1020 * we use a structure.
1023 struct cli_iterator {
1024 struct ast_cli_entry *builtins;
1025 struct ast_cli_entry *helpers;
1028 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
1030 struct ast_cli_entry *e;
1032 if (i->builtins == NULL && i->helpers == NULL) {
1034 i->builtins = builtins;
1035 i->helpers = AST_LIST_FIRST(&helpers);
1037 e = i->builtins; /* temporary */
1038 if (!e->cmda[0] || (i->helpers &&
1039 strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
1043 i->helpers = AST_LIST_NEXT(e, list);
1044 } else { /* use builtin. e is already set */
1045 (i->builtins)++; /* move to next */
1051 * \brief locate a cli command in the 'helpers' list (which must be locked).
1052 * exact has 3 values:
1053 * 0 returns if the search key is equal or longer than the entry.
1054 * -1 true if the mismatch is on the last word XXX not true!
1055 * 1 true only on complete, exact match.
1057 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1059 int matchlen = -1; /* length of longest match so far */
1060 struct ast_cli_entry *cand = NULL, *e=NULL;
1061 struct cli_iterator i = { NULL, NULL};
1063 while( (e = cli_next(&i)) ) {
1065 for (y = 0 ; cmds[y] && e->cmda[y]; y++) {
1066 if (strcasecmp(e->cmda[y], cmds[y]))
1069 if (e->cmda[y] == NULL) { /* no more words in candidate */
1070 if (cmds[y] == NULL) /* this is an exact match, cannot do better */
1072 /* here the search key is longer than the candidate */
1073 if (match_type != 0) /* but we look for almost exact match... */
1074 continue; /* so we skip this one. */
1075 /* otherwise we like it (case 0) */
1076 } else { /* still words in candidate */
1077 if (cmds[y] == NULL) /* search key is shorter, not good */
1079 /* if we get here, both words exist but there is a mismatch */
1080 if (match_type == 0) /* not the one we look for */
1082 if (match_type == 1) /* not the one we look for */
1084 if (cmds[y+1] != NULL || e->cmda[y+1] != NULL) /* not the one we look for */
1086 /* we are in case match_type == -1 and mismatch on last word */
1088 if (cand == NULL || y > matchlen) /* remember the candidate */
1091 return e ? e : cand;
1094 static char *find_best(char *argv[])
1096 static char cmdline[80];
1098 /* See how close we get, then print the candidate */
1099 char *myargv[AST_MAX_CMD_LEN];
1100 for (x=0;x<AST_MAX_CMD_LEN;x++)
1102 AST_LIST_LOCK(&helpers);
1103 for (x=0;argv[x];x++) {
1104 myargv[x] = argv[x];
1105 if (!find_cli(myargv, -1))
1108 AST_LIST_UNLOCK(&helpers);
1109 ast_join(cmdline, sizeof(cmdline), myargv);
1113 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1115 if (e->deprecate_cmd) {
1116 __ast_cli_unregister(e->deprecate_cmd, e);
1119 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1121 AST_LIST_LOCK(&helpers);
1122 AST_LIST_REMOVE(&helpers, e, list);
1123 AST_LIST_UNLOCK(&helpers);
1128 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1130 struct ast_cli_entry *cur;
1134 ast_join(fulle, sizeof(fulle), e->cmda);
1135 AST_LIST_LOCK(&helpers);
1137 if (find_cli(e->cmda, 1)) {
1138 AST_LIST_UNLOCK(&helpers);
1139 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1142 e->_full_cmd = ast_strdup(fulle);
1148 e->summary = ed->summary;
1149 e->usage = ed->usage;
1150 /* XXX If command A deprecates command B, and command B deprecates command C...
1151 Do we want to show command A or command B when telling the user to use new syntax?
1152 This currently would show command A.
1153 To show command B, you just need to always use ed->_full_cmd.
1155 e->_deprecated_by = S_OR(ed->_deprecated_by, ed->_full_cmd);
1161 AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1162 int len = strlen(cur->_full_cmd);
1165 if (strncasecmp(fulle, cur->_full_cmd, len) < 0) {
1166 AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list);
1170 AST_LIST_TRAVERSE_SAFE_END;
1173 AST_LIST_INSERT_TAIL(&helpers, e, list);
1174 ret = 0; /* success */
1177 AST_LIST_UNLOCK(&helpers);
1179 if (e->deprecate_cmd) {
1180 /* This command deprecates another command. Register that one also. */
1181 __ast_cli_register(e->deprecate_cmd, e);
1187 /* wrapper function, so we can unregister deprecated commands recursively */
1188 int ast_cli_unregister(struct ast_cli_entry *e)
1190 return __ast_cli_unregister(e, NULL);
1193 /* wrapper function, so we can register deprecated commands recursively */
1194 int ast_cli_register(struct ast_cli_entry *e)
1196 return __ast_cli_register(e, NULL);
1200 * register/unregister an array of entries.
1202 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1206 for (i = 0; i < len; i++)
1207 ast_cli_register(e + i);
1210 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1214 for (i = 0; i < len; i++)
1215 ast_cli_unregister(e + i);
1219 /*! \brief helper for help_workhorse and final part of
1220 * handle_help. if locked = 0 it's just help_workhorse,
1221 * otherwise assume the list is already locked and print
1222 * an error message if not found.
1224 static int help1(int fd, char *match[], int locked)
1226 char matchstr[80] = "";
1227 struct ast_cli_entry *e;
1230 struct cli_iterator i = { NULL, NULL};
1233 ast_join(matchstr, sizeof(matchstr), match);
1234 len = strlen(matchstr);
1237 AST_LIST_LOCK(&helpers);
1238 while ( (e = cli_next(&i)) ) {
1239 /* Hide commands that start with '_' */
1240 if (e->_full_cmd[0] == '_')
1242 /* Hide commands that are marked as deprecated. */
1245 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1247 ast_cli(fd, "%25.25s %s\n", e->_full_cmd, e->summary);
1250 AST_LIST_UNLOCK(&helpers);
1251 if (!locked && !found && matchstr[0])
1252 ast_cli(fd, "No such command '%s'.\n", matchstr);
1256 static int help_workhorse(int fd, char *match[])
1258 return help1(fd, match, 0 /* do not print errors */);
1261 static int handle_help(int fd, int argc, char *argv[])
1264 struct ast_cli_entry *e;
1267 return RESULT_SHOWUSAGE;
1269 return help_workhorse(fd, NULL);
1271 AST_LIST_LOCK(&helpers);
1272 e = find_cli(argv + 1, 1); /* try exact match first */
1274 return help1(fd, argv + 1, 1 /* locked */);
1276 ast_cli(fd, "%s", e->usage);
1278 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1279 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1281 AST_LIST_UNLOCK(&helpers);
1282 return RESULT_SUCCESS;
1285 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1293 *trailingwhitespace = 0;
1294 if (s == NULL) /* invalid, though! */
1296 /* make a copy to store the parsed string */
1297 if (!(dup = ast_strdup(s)))
1301 /* scan the original string copying into cur when needed */
1304 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1307 if (*s == '"' && !escaped) {
1309 if (quoted && whitespace) {
1310 /* start a quoted string from previous whitespace: new argument */
1314 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1315 /* If we are not already in whitespace, and not in a quoted string or
1316 processing an escape sequence, and just entered whitespace, then
1317 finalize the previous argument and remember that we are in whitespace
1323 } else if (*s == '\\' && !escaped) {
1327 /* we leave whitespace, and are not quoted. So it's a new argument */
1335 /* Null terminate */
1337 /* XXX put a NULL in the last argument, because some functions that take
1338 * the array may want a null-terminated array.
1339 * argc still reflects the number of non-NULL entries.
1343 *trailingwhitespace = whitespace;
1347 /*! \brief Return the number of unique matches for the generator */
1348 int ast_cli_generatornummatches(const char *text, const char *word)
1350 int matches = 0, i = 0;
1351 char *buf = NULL, *oldbuf = NULL;
1353 while ((buf = ast_cli_generator(text, word, i++))) {
1354 if (!oldbuf || strcmp(buf,oldbuf))
1365 char **ast_cli_completion_matches(const char *text, const char *word)
1367 char **match_list = NULL, *retstr, *prevstr;
1368 size_t match_list_len, max_equal, which, i;
1371 /* leave entry 0 free for the longest common substring */
1373 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1374 if (matches + 1 >= match_list_len) {
1375 match_list_len <<= 1;
1376 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1379 match_list[++matches] = retstr;
1383 return match_list; /* NULL */
1385 /* Find the longest substring that is common to all results
1386 * (it is a candidate for completion), and store a copy in entry 0.
1388 prevstr = match_list[1];
1389 max_equal = strlen(prevstr);
1390 for (which = 2; which <= matches; which++) {
1391 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1396 if (!(retstr = ast_malloc(max_equal + 1)))
1399 strncpy(retstr, match_list[1], max_equal);
1400 retstr[max_equal] = '\0';
1401 match_list[0] = retstr;
1403 /* ensure that the array is NULL terminated */
1404 if (matches + 1 >= match_list_len) {
1405 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1408 match_list[matches + 1] = NULL;
1413 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1415 char *argv[AST_MAX_ARGS];
1416 struct ast_cli_entry *e;
1417 struct cli_iterator i = { NULL, NULL };
1418 int x = 0, argindex, matchlen;
1421 char matchstr[80] = "";
1423 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1425 if (!dup) /* error */
1427 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1428 /* rebuild the command, ignore tws */
1429 ast_join(matchstr, sizeof(matchstr)-1, argv);
1430 matchlen = strlen(matchstr);
1432 strcat(matchstr, " "); /* XXX */
1437 AST_LIST_LOCK(&helpers);
1438 while( !ret && (e = cli_next(&i)) ) {
1439 int lc = strlen(e->_full_cmd);
1440 if (e->_full_cmd[0] != '_' && lc > 0 && matchlen <= lc &&
1441 !strncasecmp(matchstr, e->_full_cmd, matchlen)) {
1442 /* Found initial part, return a copy of the next word... */
1443 if (e->cmda[argindex] && ++matchnum > state)
1444 ret = strdup(e->cmda[argindex]); /* we need a malloced string */
1445 } else if (e->generator && !strncasecmp(matchstr, e->_full_cmd, lc) && matchstr[lc] < 33) {
1446 /* We have a command in its entirity within us -- theoretically only one
1447 command can have this occur */
1448 ret = e->generator(matchstr, word, argindex, state);
1452 AST_LIST_UNLOCK(&helpers);
1457 char *ast_cli_generator(const char *text, const char *word, int state)
1459 return __ast_cli_generator(text, word, state, 1);
1462 int ast_cli_command(int fd, const char *s)
1464 char *argv[AST_MAX_ARGS];
1465 struct ast_cli_entry *e;
1470 if (!(dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws)))
1473 /* We need at least one entry, or ignore */
1475 AST_LIST_LOCK(&helpers);
1476 e = find_cli(argv, 0);
1479 AST_LIST_UNLOCK(&helpers);
1481 switch(e->handler(fd, x, argv)) {
1482 case RESULT_SHOWUSAGE:
1484 ast_cli(fd, "%s", e->usage);
1486 ast_cli(fd, "Invalid usage, but no usage information available.\n");
1489 AST_LIST_LOCK(&helpers);
1490 if (e->deprecated == 1) {
1491 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);
1494 AST_LIST_UNLOCK(&helpers);
1498 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1500 ast_atomic_fetchadd_int(&e->inuse, -1);