2 * Asterisk -- A telephony toolkit for Linux.
4 * Standard Command Line Interface
6 * Copyright (C) 1999 - 2005, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
16 #include <asterisk/logger.h>
17 #include <asterisk/options.h>
18 #include <asterisk/cli.h>
19 #include <asterisk/module.h>
20 #include <asterisk/pbx.h>
21 #include <asterisk/channel.h>
22 #include <asterisk/channel_pvt.h>
23 #include <asterisk/manager.h>
24 #include <asterisk/utils.h>
25 #include <asterisk/lock.h>
26 #include <sys/signal.h>
31 /* For rl_filename_completion */
32 #include "editline/readline/readline.h"
33 /* For module directory */
38 #define VERSION_INFO "Asterisk " ASTERISK_VERSION " built by " BUILD_USER "@" BUILD_HOSTNAME \
39 " on a " BUILD_MACHINE " running " BUILD_OS
41 extern unsigned long global_fin, global_fout;
43 void ast_cli(int fd, char *fmt, ...)
51 stuff = (char *)malloc(10240);
52 vsnprintf(stuff, 10240, fmt, ap);
54 res = vasprintf(&stuff, fmt, ap);
58 ast_log(LOG_ERROR, "Out of memory\n");
60 ast_carefulwrite(fd, stuff, strlen(stuff), 100);
65 AST_MUTEX_DEFINE_STATIC(clilock);
67 struct ast_cli_entry *helpers = NULL;
69 static char load_help[] =
70 "Usage: load <module name>\n"
71 " Loads the specified module into Asterisk.\n";
73 static char unload_help[] =
74 "Usage: unload [-f|-h] <module name>\n"
75 " Unloads the specified module from Asterisk. The -f\n"
76 " option causes the module to be unloaded even if it is\n"
77 " in use (may cause a crash) and the -h module causes the\n"
78 " module to be unloaded even if the module says it cannot, \n"
79 " which almost always will cause a crash.\n";
81 static char help_help[] =
82 "Usage: help [topic]\n"
83 " When called with a topic as an argument, displays usage\n"
84 " information on the given command. If called without a\n"
85 " topic, it provides a list of commands.\n";
87 static char chanlist_help[] =
88 "Usage: show channels [concise]\n"
89 " Lists currently defined channels and some information about\n"
90 " them. If 'concise' is specified, format is abridged and in\n"
91 " a more easily machine parsable format\n";
93 static char reload_help[] =
94 "Usage: reload [module ...]\n"
95 " Reloads configuration files for all listed modules which support\n"
96 " reloading, or for all supported modules if none are listed.\n";
98 static char set_verbose_help[] =
99 "Usage: set verbose <level>\n"
100 " Sets level of verbose messages to be displayed. 0 means\n"
101 " no messages should be displayed. Equivalent to -v[v[v...]]\n"
104 static char set_debug_help[] =
105 "Usage: set debug <level>\n"
106 " Sets level of core debug messages to be displayed. 0 means\n"
107 " no messages should be displayed. Equivalent to -d[d[d...]]\n"
110 static char softhangup_help[] =
111 "Usage: soft hangup <channel>\n"
112 " Request that a channel be hung up. The hangup takes effect\n"
113 " the next time the driver reads or writes from the channel\n";
115 static int handle_load(int fd, int argc, char *argv[])
118 return RESULT_SHOWUSAGE;
119 if (ast_load_resource(argv[1])) {
120 ast_cli(fd, "Unable to load module %s\n", argv[1]);
121 return RESULT_FAILURE;
123 return RESULT_SUCCESS;
126 static int handle_reload(int fd, int argc, char *argv[])
131 return RESULT_SHOWUSAGE;
133 for (x=1;x<argc;x++) {
134 res = ast_module_reload(argv[x]);
137 ast_cli(fd, "No such module '%s'\n", argv[x]);
140 ast_cli(fd, "Module '%s' does not support reload\n", argv[x]);
145 ast_module_reload(NULL);
146 return RESULT_SUCCESS;
149 static int handle_set_verbose(int fd, int argc, char *argv[])
154 /* Has a hidden 'at least' argument */
155 if ((argc != 3) && (argc != 4))
156 return RESULT_SHOWUSAGE;
157 if ((argc == 4) && strcasecmp(argv[2], "atleast"))
158 return RESULT_SHOWUSAGE;
159 oldval = option_verbose;
161 option_verbose = atoi(argv[2]);
164 if (val > option_verbose)
165 option_verbose = val;
167 if (oldval != option_verbose && option_verbose > 0)
168 ast_cli(fd, "Verbosity was %d and is now %d\n", oldval, option_verbose);
169 else if (oldval > 0 && option_verbose > 0)
170 ast_cli(fd, "Verbosity is at least %d\n", option_verbose);
171 else if (oldval > 0 && option_verbose == 0)
172 ast_cli(fd, "Verbosity is now OFF\n");
173 return RESULT_SUCCESS;
176 static int handle_set_debug(int fd, int argc, char *argv[])
180 /* Has a hidden 'at least' argument */
181 if ((argc != 3) && (argc != 4))
182 return RESULT_SHOWUSAGE;
183 if ((argc == 4) && strcasecmp(argv[2], "atleast"))
184 return RESULT_SHOWUSAGE;
185 oldval = option_debug;
187 option_debug = atoi(argv[2]);
190 if (val > option_debug)
193 if (oldval != option_debug && option_debug > 0)
194 ast_cli(fd, "Core debug was %d and is now %d\n", oldval, option_debug);
195 else if (oldval > 0 && option_debug > 0)
196 ast_cli(fd, "Core debug is at least %d\n", option_debug);
197 else if (oldval > 0 && option_debug == 0)
198 ast_cli(fd, "Core debug is now OFF\n");
199 return RESULT_SUCCESS;
202 static int handle_unload(int fd, int argc, char *argv[])
205 int force=AST_FORCE_SOFT;
207 return RESULT_SHOWUSAGE;
208 for (x=1;x<argc;x++) {
209 if (argv[x][0] == '-') {
212 force = AST_FORCE_FIRM;
215 force = AST_FORCE_HARD;
218 return RESULT_SHOWUSAGE;
220 } else if (x != argc - 1)
221 return RESULT_SHOWUSAGE;
222 else if (ast_unload_resource(argv[x], force)) {
223 ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
224 return RESULT_FAILURE;
227 return RESULT_SUCCESS;
230 #define MODLIST_FORMAT "%-25s %-40.40s %-10d\n"
231 #define MODLIST_FORMAT2 "%-25s %-40.40s %-10s\n"
233 AST_MUTEX_DEFINE_STATIC(climodentrylock);
234 static int climodentryfd = -1;
236 static int modlist_modentry(char *module, char *description, int usecnt, char *like)
238 /* Comparing the like with the module */
239 if ( strstr(module,like) != NULL) {
240 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
247 static char modlist_help[] =
248 "Usage: show modules [like keyword]\n"
249 " Shows Asterisk modules currently in use, and usage statistics.\n";
251 static char version_help[] =
252 "Usage: show version\n"
253 " Shows Asterisk version information.\n";
255 static char uptime_help[] =
256 "Usage: show uptime [seconds]\n"
257 " Shows Asterisk uptime information.\n"
258 " The seconds word returns the uptime in seconds only.\n";
260 static char *format_uptimestr(time_t timeval)
262 int years = 0, weeks = 0, days = 0, hours = 0, mins = 0, secs = 0;
263 char timestr[256]="";
268 #define MINUTE (SECOND*60)
269 #define HOUR (MINUTE*60)
270 #define DAY (HOUR*24)
272 #define YEAR (DAY*365)
273 #define ESS(x) ((x == 1) ? "" : "s")
275 maxbytes = sizeof(timestr);
278 if (timeval > YEAR) {
279 years = (timeval / YEAR);
280 timeval -= (years * YEAR);
282 snprintf(timestr + offset, maxbytes, "%d year%s, ", years, ESS(years));
283 bytes = strlen(timestr + offset);
288 if (timeval > WEEK) {
289 weeks = (timeval / WEEK);
290 timeval -= (weeks * WEEK);
292 snprintf(timestr + offset, maxbytes, "%d week%s, ", weeks, ESS(weeks));
293 bytes = strlen(timestr + offset);
299 days = (timeval / DAY);
300 timeval -= (days * DAY);
302 snprintf(timestr + offset, maxbytes, "%d day%s, ", days, ESS(days));
303 bytes = strlen(timestr + offset);
308 if (timeval > HOUR) {
309 hours = (timeval / HOUR);
310 timeval -= (hours * HOUR);
312 snprintf(timestr + offset, maxbytes, "%d hour%s, ", hours, ESS(hours));
313 bytes = strlen(timestr + offset);
318 if (timeval > MINUTE) {
319 mins = (timeval / MINUTE);
320 timeval -= (mins * MINUTE);
322 snprintf(timestr + offset, maxbytes, "%d minute%s, ", mins, ESS(mins));
323 bytes = strlen(timestr + offset);
331 snprintf(timestr + offset, maxbytes, "%d second%s", secs, ESS(secs));
334 return timestr ? strdup(timestr) : NULL;
337 static int handle_showuptime(int fd, int argc, char *argv[])
339 time_t curtime, tmptime;
343 printsec = ((argc == 3) && (!strcasecmp(argv[2],"seconds")));
344 if ((argc != 2) && (!printsec))
345 return RESULT_SHOWUSAGE;
348 if (ast_startuptime) {
349 tmptime = curtime - ast_startuptime;
351 ast_cli(fd, "System uptime: %lu\n",tmptime);
353 timestr = format_uptimestr(tmptime);
355 ast_cli(fd, "System uptime: %s\n", timestr);
360 if (ast_lastreloadtime) {
361 tmptime = curtime - ast_lastreloadtime;
363 ast_cli(fd, "Last reload: %lu\n", tmptime);
365 timestr = format_uptimestr(tmptime);
366 if ((timestr) && (!printsec)) {
367 ast_cli(fd, "Last reload: %s\n", timestr);
372 return RESULT_SUCCESS;
375 static int handle_modlist(int fd, int argc, char *argv[])
379 return RESULT_SHOWUSAGE;
380 else if (argc >= 4) {
381 if ( strcmp(argv[2],"like") )
382 return RESULT_SHOWUSAGE;
386 ast_mutex_lock(&climodentrylock);
388 ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
389 ast_cli(fd,"%d modules loaded\n",ast_update_module_list(modlist_modentry,like));
391 ast_mutex_unlock(&climodentrylock);
392 return RESULT_SUCCESS;
395 static int handle_version(int fd, int argc, char *argv[])
398 return RESULT_SHOWUSAGE;
399 ast_cli(fd, "%s\n", VERSION_INFO);
400 return RESULT_SUCCESS;
402 static int handle_chanlist(int fd, int argc, char *argv[])
404 #define FORMAT_STRING "%15s (%-10s %-12s %-4d) %7s %-12s %-15s\n"
405 #define FORMAT_STRING2 "%15s (%-10s %-12s %-4s) %7s %-12s %-15s\n"
406 #define CONCISE_FORMAT_STRING "%s:%s:%s:%d:%s:%s:%s:%s:%s:%d\n"
408 struct ast_channel *c=NULL;
411 if (argc < 2 || argc > 3)
412 return RESULT_SHOWUSAGE;
414 concise = (argc == 3 && (!strcasecmp(argv[2],"concise")));
415 c = ast_channel_walk_locked(NULL);
417 ast_cli(fd, FORMAT_STRING2, "Channel", "Context", "Extension", "Pri", "State", "Appl.", "Data");
420 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
421 c->appl ? c->appl : "(None)", c->data ? ( !ast_strlen_zero(c->data) ? c->data : "" ): "",
422 (c->cid.cid_num && !ast_strlen_zero(c->cid.cid_num)) ? c->cid.cid_num : "",
423 (c->accountcode && !ast_strlen_zero(c->accountcode)) ? c->accountcode : "",c->amaflags);
425 ast_cli(fd, FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
426 c->appl ? c->appl : "(None)", c->data ? ( !ast_strlen_zero(c->data) ? c->data : "(Empty)" ): "(None)");
429 ast_mutex_unlock(&c->lock);
430 c = ast_channel_walk_locked(c);
433 ast_cli(fd, "%d active channel(s)\n", numchans);
434 return RESULT_SUCCESS;
437 static char showchan_help[] =
438 "Usage: show channel <channel>\n"
439 " Shows lots of information about the specified channel.\n";
441 static char debugchan_help[] =
442 "Usage: debug channel <channel>\n"
443 " Enables debugging on a specific channel.\n";
445 static char nodebugchan_help[] =
446 "Usage: no debug channel <channel>\n"
447 " Disables debugging on a specific channel.\n";
449 static char commandcomplete_help[] =
450 "Usage: _command complete \"<line>\" text state\n"
451 " This function is used internally to help with command completion and should.\n"
452 " never be called by the user directly.\n";
454 static char commandnummatches_help[] =
455 "Usage: _command nummatches \"<line>\" text \n"
456 " This function is used internally to help with command completion and should.\n"
457 " never be called by the user directly.\n";
459 static char commandmatchesarray_help[] =
460 "Usage: _command matchesarray \"<line>\" text \n"
461 " This function is used internally to help with command completion and should.\n"
462 " never be called by the user directly.\n";
464 static int handle_softhangup(int fd, int argc, char *argv[])
466 struct ast_channel *c=NULL;
468 return RESULT_SHOWUSAGE;
469 c = ast_channel_walk_locked(NULL);
471 if (!strcasecmp(c->name, argv[2])) {
472 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
473 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
474 ast_mutex_unlock(&c->lock);
477 ast_mutex_unlock(&c->lock);
478 c = ast_channel_walk_locked(c);
481 ast_cli(fd, "%s is not a known channel\n", argv[2]);
482 return RESULT_SUCCESS;
485 static char *__ast_cli_generator(char *text, char *word, int state, int lock);
487 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
496 return RESULT_SHOWUSAGE;
497 buf = malloc(buflen);
499 return RESULT_FAILURE;
501 matches = ast_cli_completion_matches(argv[2], argv[3]);
503 for (x=0; matches[x]; x++) {
505 printf("command matchesarray for '%s' %s got '%s'\n", argv[2], argv[3], matches[x]);
507 matchlen = strlen(matches[x]) + 1;
508 if (len + matchlen >= buflen) {
509 buflen += matchlen * 3;
511 buf = realloc(obuf, buflen);
513 /* Out of memory... Just free old buffer and be done */
517 len += sprintf( buf + len, "%s ", matches[x]);
524 printf("array for '%s' %s got '%s'\n", argv[2], argv[3], buf);
528 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
531 ast_cli(fd, "NULL\n");
533 return RESULT_SUCCESS;
538 static int handle_commandnummatches(int fd, int argc, char *argv[])
543 return RESULT_SHOWUSAGE;
545 matches = ast_cli_generatornummatches(argv[2], argv[3]);
548 printf("Search for '%s' %s got '%d'\n", argv[2], argv[3], matches);
550 ast_cli(fd, "%d", matches);
552 return RESULT_SUCCESS;
555 static int handle_commandcomplete(int fd, int argc, char *argv[])
559 printf("Search for %d args: '%s', '%s', '%s', '%s'\n", argc, argv[0], argv[1], argv[2], argv[3]);
562 return RESULT_SHOWUSAGE;
563 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
565 printf("Search for '%s' %s %d got '%s'\n", argv[2], argv[3], atoi(argv[4]), buf);
571 ast_cli(fd, "NULL\n");
572 return RESULT_SUCCESS;
575 static int handle_debugchan(int fd, int argc, char *argv[])
577 struct ast_channel *c=NULL;
580 return RESULT_SHOWUSAGE;
582 is_all = !strcasecmp("all", argv[2]);
584 global_fin |= 0x80000000;
585 global_fout |= 0x80000000;
587 c = ast_channel_walk_locked(NULL);
589 if (is_all || !strcasecmp(c->name, argv[2])) {
590 if (!(c->fin & 0x80000000) || !(c->fout & 0x80000000)) {
591 c->fin |= 0x80000000;
592 c->fout |= 0x80000000;
593 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
598 ast_mutex_unlock(&c->lock);
599 c = ast_channel_walk_locked(c);
603 ast_mutex_unlock(&c->lock);
605 ast_cli(fd, "No such channel %s\n", argv[2]);
608 ast_cli(fd, "Debugging on new channels is enabled\n");
609 return RESULT_SUCCESS;
612 static int handle_nodebugchan(int fd, int argc, char *argv[])
614 struct ast_channel *c=NULL;
617 return RESULT_SHOWUSAGE;
618 is_all = !strcasecmp("all", argv[3]);
620 global_fin &= ~0x80000000;
621 global_fout &= ~0x80000000;
623 c = ast_channel_walk_locked(NULL);
625 if (is_all || !strcasecmp(c->name, argv[3])) {
626 if ((c->fin & 0x80000000) || (c->fout & 0x80000000)) {
627 c->fin &= 0x7fffffff;
628 c->fout &= 0x7fffffff;
629 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
634 ast_mutex_unlock(&c->lock);
635 c = ast_channel_walk_locked(c);
639 ast_mutex_unlock(&c->lock);
641 ast_cli(fd, "No such channel %s\n", argv[3]);
644 ast_cli(fd, "Debugging on new channels is disabled\n");
645 return RESULT_SUCCESS;
650 static int handle_showchan(int fd, int argc, char *argv[])
652 struct ast_channel *c=NULL;
656 long elapsed_seconds=0;
657 int hour=0, min=0, sec=0;
660 return RESULT_SHOWUSAGE;
661 gettimeofday(&now, NULL);
662 c = ast_channel_walk_locked(NULL);
664 if (!strcasecmp(c->name, argv[2])) {
666 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
667 hour = elapsed_seconds / 3600;
668 min = (elapsed_seconds % 3600) / 60;
669 sec = elapsed_seconds % 60;
670 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
672 strncpy(cdrtime, "N/A", sizeof(cdrtime) -1);
679 " Caller ID Name: %s\n"
683 " NativeFormat: %d\n"
686 "1st File Descriptor: %d\n"
688 " Frames out: %d%s\n"
689 " Time to Hangup: %ld\n"
690 " Elapsed Time: %s\n"
691 " Direct Bridge: %s\n"
692 "Indirect Bridge: %s\n"
698 " Pickup Group: %d\n"
701 " Blocking in: %s\n",
702 c->name, c->type, c->uniqueid,
703 (c->cid.cid_num ? c->cid.cid_num : "(N/A)"),
704 (c->cid.cid_name ? c->cid.cid_name : "(N/A)"),
705 (c->cid.cid_dnid ? c->cid.cid_dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings, c->nativeformats, c->writeformat, c->readformat,
706 c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
707 c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", (long)c->whentohangup,
708 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
709 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
710 ( c-> data ? (!ast_strlen_zero(c->data) ? c->data : "(Empty)") : "(None)"),
711 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
712 if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
713 ast_cli(fd," Variables:\n%s\n",buf);
714 if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
715 ast_cli(fd," CDR Variables:\n%s\n",buf);
717 ast_mutex_unlock(&c->lock);
720 ast_mutex_unlock(&c->lock);
721 c = ast_channel_walk_locked(c);
724 ast_cli(fd, "%s is not a known channel\n", argv[2]);
725 return RESULT_SUCCESS;
728 static char *complete_ch_helper(char *line, char *word, int pos, int state, int rpos)
730 struct ast_channel *c;
735 c = ast_channel_walk_locked(NULL);
737 if (!strncasecmp(word, c->name, strlen(word))) {
741 ast_mutex_unlock(&c->lock);
742 c = ast_channel_walk_locked(c);
745 ret = strdup(c->name);
746 ast_mutex_unlock(&c->lock);
752 static char *complete_ch_3(char *line, char *word, int pos, int state)
754 return complete_ch_helper(line, word, pos, state, 2);
757 static char *complete_ch_4(char *line, char *word, int pos, int state)
759 return complete_ch_helper(line, word, pos, state, 3);
762 static char *complete_mod_2(char *line, char *word, int pos, int state)
764 return ast_module_helper(line, word, pos, state, 1, 1);
767 static char *complete_mod_4(char *line, char *word, int pos, int state)
769 return ast_module_helper(line, word, pos, state, 3, 0);
772 static char *complete_fn(char *line, char *word, int pos, int state)
779 strncpy(filename, word, sizeof(filename)-1);
781 snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_MODULE_DIR, word);
782 c = (char*)filename_completion_function(filename, state);
783 if (c && word[0] != '/')
784 c += (strlen((char*)ast_config_AST_MODULE_DIR) + 1);
785 return c ? strdup(c) : c;
788 static int handle_help(int fd, int argc, char *argv[]);
790 static struct ast_cli_entry builtins[] = {
791 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
792 { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
793 { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
794 { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
795 { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch_3 },
796 { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help },
797 { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
798 { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch_4 },
799 { { "reload", NULL }, handle_reload, "Reload configuration", reload_help, complete_mod_2 },
800 { { "set", "debug", NULL }, handle_set_debug, "Set level of debug chattiness", set_debug_help },
801 { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
802 { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch_3 },
803 { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help },
804 { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
805 { { "show", "modules", "like", NULL }, handle_modlist, "List modules and info", modlist_help, complete_mod_4 },
806 { { "show", "uptime", NULL }, handle_showuptime, "Show uptime information", uptime_help },
807 { { "show", "version", NULL }, handle_version, "Display version info", version_help },
808 { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch_3 },
809 { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
810 { { NULL }, NULL, NULL, NULL }
813 static struct ast_cli_entry *find_cli(char *cmds[], int exact)
818 struct ast_cli_entry *e=NULL;
819 for (x=0;builtins[x].cmda[0];x++) {
820 /* start optimistic */
822 for (y=0;match && cmds[y]; y++) {
823 /* If there are no more words in the candidate command, then we're
825 if (!builtins[x].cmda[y] && !exact)
827 /* If there are no more words in the command (and we're looking for
828 an exact match) or there is a difference between the two words,
829 then this is not a match */
830 if (!builtins[x].cmda[y] || strcasecmp(builtins[x].cmda[y], cmds[y]))
833 /* If more words are needed to complete the command then this is not
834 a candidate (unless we're looking for a really inexact answer */
835 if ((exact > -1) && builtins[x].cmda[y])
840 for (e=helpers;e;e=e->next) {
842 for (y=0;match && cmds[y]; y++) {
843 if (!e->cmda[y] && !exact)
845 if (!e->cmda[y] || strcasecmp(e->cmda[y], cmds[y]))
848 if ((exact > -1) && e->cmda[y])
856 static void join(char *dest, size_t destsize, char *w[])
859 /* Join words into a string */
860 if (!dest || destsize < 1) {
866 strncat(dest, " ", destsize - strlen(dest) - 1);
867 strncat(dest, w[x], destsize - strlen(dest) - 1);
871 static void join2(char *dest, size_t destsize, char *w[])
874 /* Join words into a string */
875 if (!dest || destsize < 1) {
880 strncat(dest, w[x], destsize - strlen(dest) - 1);
884 static char *find_best(char *argv[])
886 static char cmdline[80];
888 /* See how close we get, then print the */
889 char *myargv[AST_MAX_CMD_LEN];
890 for (x=0;x<AST_MAX_CMD_LEN;x++)
892 for (x=0;argv[x];x++) {
894 if (!find_cli(myargv, -1))
897 join(cmdline, sizeof(cmdline), myargv);
901 int ast_cli_unregister(struct ast_cli_entry *e)
903 struct ast_cli_entry *cur, *l=NULL;
904 ast_mutex_lock(&clilock);
909 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
923 ast_mutex_unlock(&clilock);
927 int ast_cli_register(struct ast_cli_entry *e)
929 struct ast_cli_entry *cur, *l=NULL;
930 char fulle[80] ="", fulltst[80] ="";
932 ast_mutex_lock(&clilock);
933 join2(fulle, sizeof(fulle), e->cmda);
934 if (find_cli(e->cmda, -1)) {
935 ast_mutex_unlock(&clilock);
936 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
941 join2(fulltst, sizeof(fulltst), cur->cmda);
942 len = strlen(fulltst);
943 if (strlen(fulle) < len)
945 if (strncasecmp(fulle, fulltst, len) < 0) {
965 ast_mutex_unlock(&clilock);
969 static int help_workhorse(int fd, char *match[])
971 char fullcmd1[80] = "";
972 char fullcmd2[80] = "";
974 char *fullcmd = NULL;
975 struct ast_cli_entry *e, *e1, *e2;
979 join(matchstr, sizeof(matchstr), match);
980 while(e1->cmda[0] || e2) {
982 join(fullcmd2, sizeof(fullcmd2), e2->cmda);
984 join(fullcmd1, sizeof(fullcmd1), e1->cmda);
986 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
990 /* Increment by going to next */
998 /* Hide commands that start with '_' */
999 if (fullcmd[0] == '_')
1002 if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1006 ast_cli(fd, "%25.25s %s\n", fullcmd, e->summary);
1011 static int handle_help(int fd, int argc, char *argv[]) {
1012 struct ast_cli_entry *e;
1015 return RESULT_SHOWUSAGE;
1017 e = find_cli(argv + 1, 1);
1019 ast_cli(fd, e->usage);
1021 if (find_cli(argv + 1, -1)) {
1022 return help_workhorse(fd, argv + 1);
1024 join(fullcmd, sizeof(fullcmd), argv+1);
1025 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1029 return help_workhorse(fd, NULL);
1031 return RESULT_SUCCESS;
1034 static char *parse_args(char *s, int *max, char *argv[])
1048 /* If it's escaped, put a literal quote */
1053 if (quoted && whitespace) {
1054 /* If we're starting a quote, coming off white space start a new word, too */
1062 if (!quoted && !escaped) {
1063 /* If we're not quoted, mark this as whitespace, and
1064 end the previous argument */
1068 /* Otherwise, just treat it as anything else */
1072 /* If we're escaped, print a literal, otherwise enable escaping */
1082 if (x >= AST_MAX_ARGS -1) {
1083 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1086 /* Coming off of whitespace, start the next argument */
1095 /* Null terminate */
1103 /* This returns the number of unique matches for the generator */
1104 int ast_cli_generatornummatches(char *text, char *word)
1106 int matches = 0, i = 0;
1107 char *buf = NULL, *oldbuf = NULL;
1109 while ( (buf = ast_cli_generator(text, word, i)) ) {
1110 if (++i > 1 && strcmp(buf,oldbuf) == 0) {
1120 char **ast_cli_completion_matches(char *text, char *word)
1122 char **match_list = NULL, *retstr, *prevstr;
1123 size_t match_list_len, max_equal, which, i;
1127 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1128 if (matches + 1 >= match_list_len) {
1129 match_list_len <<= 1;
1130 match_list = realloc(match_list, match_list_len * sizeof(char *));
1132 match_list[++matches] = retstr;
1136 return (char **) NULL;
1139 prevstr = match_list[1];
1140 max_equal = strlen(prevstr);
1141 for (; which <= matches; which++) {
1142 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1147 retstr = malloc(max_equal + 1);
1148 (void) strncpy(retstr, match_list[1], max_equal);
1149 retstr[max_equal] = '\0';
1150 match_list[0] = retstr;
1152 if (matches + 1 >= match_list_len)
1153 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1154 match_list[matches + 1] = (char *) NULL;
1156 return (match_list);
1159 static char *__ast_cli_generator(char *text, char *word, int state, int lock)
1161 char *argv[AST_MAX_ARGS];
1162 struct ast_cli_entry *e, *e1, *e2;
1166 char fullcmd1[80] = "";
1167 char fullcmd2[80] = "";
1169 char *fullcmd = NULL;
1171 if ((dup = parse_args(text, &x, argv))) {
1172 join(matchstr, sizeof(matchstr), argv);
1174 ast_mutex_lock(&clilock);
1177 while(e1->cmda[0] || e2) {
1179 join(fullcmd2, sizeof(fullcmd2), e2->cmda);
1181 join(fullcmd1, sizeof(fullcmd1), e1->cmda);
1183 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
1187 /* Increment by going to next */
1195 if ((fullcmd[0] != '_') && !strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1196 /* We contain the first part of one or more commands */
1197 /* Now, what we're supposed to return is the next word... */
1198 if (!ast_strlen_zero(word) && x>0) {
1205 if (matchnum > state) {
1207 ast_mutex_unlock(&clilock);
1213 if (e->generator && !strncasecmp(matchstr, fullcmd, strlen(fullcmd))) {
1214 /* We have a command in its entirity within us -- theoretically only one
1215 command can have this occur */
1216 fullcmd = e->generator(matchstr, word, (!ast_strlen_zero(word) ? (x - 1) : (x)), state);
1219 ast_mutex_unlock(&clilock);
1227 ast_mutex_unlock(&clilock);
1233 char *ast_cli_generator(char *text, char *word, int state)
1235 return __ast_cli_generator(text, word, state, 1);
1238 int ast_cli_command(int fd, char *s)
1240 char *argv[AST_MAX_ARGS];
1241 struct ast_cli_entry *e;
1245 if ((dup = parse_args(s, &x, argv))) {
1246 /* We need at least one entry, or ignore */
1248 ast_mutex_lock(&clilock);
1249 e = find_cli(argv, 0);
1252 ast_mutex_unlock(&clilock);
1254 switch(e->handler(fd, x, argv)) {
1255 case RESULT_SHOWUSAGE:
1256 ast_cli(fd, e->usage);
1260 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1262 ast_mutex_lock(&clilock);
1264 ast_mutex_unlock(&clilock);
1269 ast_log(LOG_WARNING, "Out of memory\n");