2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, 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 #include <sys/signal.h>
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39 #include "asterisk/logger.h"
40 #include "asterisk/options.h"
41 #include "asterisk/cli.h"
42 #include "asterisk/module.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/manager.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/app.h"
48 #include "asterisk/lock.h"
49 /* For rl_filename_completion */
50 #include "editline/readline/readline.h"
51 /* For module directory */
52 #include "asterisk/version.h"
54 extern const char *ast_build_hostname;
55 extern const char *ast_build_kernel;
56 extern const char *ast_build_machine;
57 extern const char *ast_build_os;
58 extern const char *ast_build_date;
59 extern const char *ast_build_user;
61 extern unsigned long global_fin, global_fout;
63 void ast_cli(int fd, char *fmt, ...)
70 res = vasprintf(&stuff, fmt, ap);
73 ast_log(LOG_ERROR, "Out of memory\n");
75 ast_carefulwrite(fd, stuff, strlen(stuff), 100);
80 AST_MUTEX_DEFINE_STATIC(clilock);
82 struct ast_cli_entry *helpers = NULL;
84 static char load_help[] =
85 "Usage: load <module name>\n"
86 " Loads the specified module into Asterisk.\n";
88 static char unload_help[] =
89 "Usage: unload [-f|-h] <module name>\n"
90 " Unloads the specified module from Asterisk. The -f\n"
91 " option causes the module to be unloaded even if it is\n"
92 " in use (may cause a crash) and the -h module causes the\n"
93 " module to be unloaded even if the module says it cannot, \n"
94 " which almost always will cause a crash.\n";
96 static char help_help[] =
97 "Usage: help [topic]\n"
98 " When called with a topic as an argument, displays usage\n"
99 " information on the given command. If called without a\n"
100 " topic, it provides a list of commands.\n";
102 static char chanlist_help[] =
103 "Usage: show channels [concise|verbose]\n"
104 " Lists currently defined channels and some information about them. If\n"
105 " 'concise' is specified, the format is abridged and in a more easily\n"
106 " machine parsable format. If 'verbose' is specified, the output includes\n"
107 " more and longer fields.\n";
109 static char reload_help[] =
110 "Usage: reload [module ...]\n"
111 " Reloads configuration files for all listed modules which support\n"
112 " reloading, or for all supported modules if none are listed.\n";
114 static char set_verbose_help[] =
115 "Usage: set verbose <level>\n"
116 " Sets level of verbose messages to be displayed. 0 means\n"
117 " no messages should be displayed. Equivalent to -v[v[v...]]\n"
120 static char set_debug_help[] =
121 "Usage: set debug <level>\n"
122 " Sets level of core debug messages to be displayed. 0 means\n"
123 " no messages should be displayed. Equivalent to -d[d[d...]]\n"
126 static char softhangup_help[] =
127 "Usage: soft hangup <channel>\n"
128 " Request that a channel be hung up. The hangup takes effect\n"
129 " the next time the driver reads or writes from the channel\n";
131 static char group_show_channels_help[] =
132 "Usage: group show channels [pattern]\n"
133 " Lists all currently active channels with channel group(s) specified.\n"
134 " Optional regular expression pattern is matched to group names for each\n"
137 static int handle_load(int fd, int argc, char *argv[])
140 return RESULT_SHOWUSAGE;
141 if (ast_load_resource(argv[1])) {
142 ast_cli(fd, "Unable to load module %s\n", argv[1]);
143 return RESULT_FAILURE;
145 return RESULT_SUCCESS;
148 static int handle_reload(int fd, int argc, char *argv[])
153 return RESULT_SHOWUSAGE;
155 for (x=1;x<argc;x++) {
156 res = ast_module_reload(argv[x]);
159 ast_cli(fd, "No such module '%s'\n", argv[x]);
162 ast_cli(fd, "Module '%s' does not support reload\n", argv[x]);
167 ast_module_reload(NULL);
168 return RESULT_SUCCESS;
171 static int handle_set_verbose(int fd, int argc, char *argv[])
176 /* Has a hidden 'at least' argument */
177 if ((argc != 3) && (argc != 4))
178 return RESULT_SHOWUSAGE;
179 if ((argc == 4) && strcasecmp(argv[2], "atleast"))
180 return RESULT_SHOWUSAGE;
181 oldval = option_verbose;
183 option_verbose = atoi(argv[2]);
186 if (val > option_verbose)
187 option_verbose = val;
189 if (oldval != option_verbose && option_verbose > 0)
190 ast_cli(fd, "Verbosity was %d and is now %d\n", oldval, option_verbose);
191 else if (oldval > 0 && option_verbose > 0)
192 ast_cli(fd, "Verbosity is at least %d\n", option_verbose);
193 else if (oldval > 0 && option_verbose == 0)
194 ast_cli(fd, "Verbosity is now OFF\n");
195 return RESULT_SUCCESS;
198 static int handle_set_debug(int fd, int argc, char *argv[])
202 /* Has a hidden 'at least' argument */
203 if ((argc != 3) && (argc != 4))
204 return RESULT_SHOWUSAGE;
205 if ((argc == 4) && strcasecmp(argv[2], "atleast"))
206 return RESULT_SHOWUSAGE;
207 oldval = option_debug;
209 option_debug = atoi(argv[2]);
212 if (val > option_debug)
215 if (oldval != option_debug && option_debug > 0)
216 ast_cli(fd, "Core debug was %d and is now %d\n", oldval, option_debug);
217 else if (oldval > 0 && option_debug > 0)
218 ast_cli(fd, "Core debug is at least %d\n", option_debug);
219 else if (oldval > 0 && option_debug == 0)
220 ast_cli(fd, "Core debug is now OFF\n");
221 return RESULT_SUCCESS;
224 static int handle_unload(int fd, int argc, char *argv[])
227 int force=AST_FORCE_SOFT;
229 return RESULT_SHOWUSAGE;
230 for (x=1;x<argc;x++) {
231 if (argv[x][0] == '-') {
234 force = AST_FORCE_FIRM;
237 force = AST_FORCE_HARD;
240 return RESULT_SHOWUSAGE;
242 } else if (x != argc - 1)
243 return RESULT_SHOWUSAGE;
244 else if (ast_unload_resource(argv[x], force)) {
245 ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
246 return RESULT_FAILURE;
249 return RESULT_SUCCESS;
252 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
253 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
255 AST_MUTEX_DEFINE_STATIC(climodentrylock);
256 static int climodentryfd = -1;
258 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
260 /* Comparing the like with the module */
261 if (strcasestr(module, like) ) {
262 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
268 static char modlist_help[] =
269 "Usage: show modules [like keyword]\n"
270 " Shows Asterisk modules currently in use, and usage statistics.\n";
272 static char version_help[] =
273 "Usage: show version\n"
274 " Shows Asterisk version information.\n";
276 static char uptime_help[] =
277 "Usage: show uptime [seconds]\n"
278 " Shows Asterisk uptime information.\n"
279 " The seconds word returns the uptime in seconds only.\n";
281 static void print_uptimestr(int fd, time_t timeval, const char *prefix, int printsec)
283 int x; /* the main part - years, weeks, etc. */
284 char timestr[256]="", *s = timestr;
285 size_t maxbytes = sizeof(timestr);
288 #define MINUTE (SECOND*60)
289 #define HOUR (MINUTE*60)
290 #define DAY (HOUR*24)
292 #define YEAR (DAY*365)
293 #define ESS(x) ((x == 1) ? "" : "s") /* plural suffix */
294 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
295 if (timeval < 0) /* invalid, nothing to show */
297 if (printsec) { /* plain seconds output */
298 ast_build_string(&s, &maxbytes, "%lu", (u_long)timeval);
299 timeval = 0; /* bypass the other cases */
301 if (timeval > YEAR) {
302 x = (timeval / YEAR);
303 timeval -= (x * YEAR);
304 ast_build_string(&s, &maxbytes, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval));
306 if (timeval > WEEK) {
307 x = (timeval / WEEK);
308 timeval -= (x * WEEK);
309 ast_build_string(&s, &maxbytes, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval));
313 timeval -= (x * DAY);
314 ast_build_string(&s, &maxbytes, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval));
316 if (timeval > HOUR) {
317 x = (timeval / HOUR);
318 timeval -= (x * HOUR);
319 ast_build_string(&s, &maxbytes, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval));
321 if (timeval > MINUTE) {
322 x = (timeval / MINUTE);
323 timeval -= (x * MINUTE);
324 ast_build_string(&s, &maxbytes, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval));
328 ast_build_string(&s, &maxbytes, "%d second%s ", x, ESS(x));
329 if (timestr[0] != '\0')
330 ast_cli(fd, "%s: %s\n", prefix, timestr);
333 static int handle_showuptime(int fd, int argc, char *argv[])
335 /* 'show uptime [seconds]' */
336 time_t curtime = time(NULL);
337 int printsec = (argc == 3 && !strcasecmp(argv[2],"seconds"));
339 if (argc != 2 && !printsec)
340 return RESULT_SHOWUSAGE;
342 print_uptimestr(fd, curtime - ast_startuptime, "System uptime", printsec);
343 if (ast_lastreloadtime)
344 print_uptimestr(fd, curtime - ast_lastreloadtime, "Last reload", printsec);
345 return RESULT_SUCCESS;
348 static int handle_modlist(int fd, int argc, char *argv[])
352 return RESULT_SHOWUSAGE;
353 else if (argc >= 4) {
354 if (strcmp(argv[2],"like"))
355 return RESULT_SHOWUSAGE;
359 ast_mutex_lock(&climodentrylock);
361 ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
362 ast_cli(fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
364 ast_mutex_unlock(&climodentrylock);
365 return RESULT_SUCCESS;
367 #undef MODLIST_FORMAT
368 #undef MODLIST_FORMAT2
370 static int handle_version(int fd, int argc, char *argv[])
373 return RESULT_SHOWUSAGE;
374 ast_cli(fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
375 ASTERISK_VERSION, ast_build_user, ast_build_hostname,
376 ast_build_machine, ast_build_os, ast_build_date);
377 return RESULT_SUCCESS;
380 static int handle_chanlist(int fd, int argc, char *argv[])
382 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
383 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
384 #define CONCISE_FORMAT_STRING "%s:%s:%s:%d:%s:%s:%s:%s:%s:%d:%s:%s\n"
385 #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"
386 #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"
388 struct ast_channel *c = NULL, *bc = NULL;
389 char durbuf[10] = "-";
393 int durh, durm, durs;
394 int numchans = 0, concise = 0, verbose = 0;
396 concise = (argc == 3 && (!strcasecmp(argv[2],"concise")));
397 verbose = (argc == 3 && (!strcasecmp(argv[2],"verbose")));
399 if (argc < 2 || argc > 3 || (argc == 3 && !concise && !verbose))
400 return RESULT_SHOWUSAGE;
402 if (!concise && !verbose)
403 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
405 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
406 "CallerID", "Duration", "Accountcode", "BridgedTo");
407 while ((c = ast_channel_walk_locked(c)) != NULL) {
408 bc = ast_bridged_channel(c);
409 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
410 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
412 durh = duration / 3600;
413 durm = (duration % 3600) / 60;
414 durs = duration % 60;
415 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
417 snprintf(durbuf, sizeof(durbuf), "%d", duration);
423 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
424 c->appl ? c->appl : "(None)", c->data ? c->data : "",
425 c->cid.cid_num ? c->cid.cid_num : "",
426 c->accountcode ? c->accountcode : "", c->amaflags,
427 durbuf, bc ? bc->name : "(None)");
428 } else if (verbose) {
429 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
430 c->appl ? c->appl : "(None)", c->data ? ( !ast_strlen_zero(c->data) ? c->data : "(Empty)" ): "(None)",
431 c->cid.cid_num ? c->cid.cid_num : "", durbuf,
432 c->accountcode ? c->accountcode : "", bc ? bc->name : "(None)");
434 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
435 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
437 strcpy(locbuf, "(None)");
439 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, c->data ? c->data : "");
441 strcpy(appdata, "(None)");
443 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
446 ast_mutex_unlock(&c->lock);
449 ast_cli(fd, "%d active channel%s\n", numchans, (numchans!=1) ? "s" : "");
451 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n", ast_active_calls(), option_maxcalls, (ast_active_calls()!=1) ? "s" : "", ((float)ast_active_calls() / (float)option_maxcalls) * 100.0);
453 ast_cli(fd, "%d active call%s\n", ast_active_calls(), (ast_active_calls()!=1) ? "s" : "");
455 return RESULT_SUCCESS;
458 #undef FORMAT_STRING2
459 #undef CONCISE_FORMAT_STRING
460 #undef VERBOSE_FORMAT_STRING
461 #undef VERBOSE_FORMAT_STRING2
464 static char showchan_help[] =
465 "Usage: show channel <channel>\n"
466 " Shows lots of information about the specified channel.\n";
468 static char debugchan_help[] =
469 "Usage: debug channel <channel>\n"
470 " Enables debugging on a specific channel.\n";
472 static char debuglevel_help[] =
473 "Usage: debug level <level> [filename]\n"
474 " Set debug to specified level (0 to disable). If filename\n"
475 "is specified, debugging will be limited to just that file.\n";
477 static char nodebugchan_help[] =
478 "Usage: no debug channel <channel>\n"
479 " Disables debugging on a specific channel.\n";
481 static char commandcomplete_help[] =
482 "Usage: _command complete \"<line>\" text state\n"
483 " This function is used internally to help with command completion and should.\n"
484 " never be called by the user directly.\n";
486 static char commandnummatches_help[] =
487 "Usage: _command nummatches \"<line>\" text \n"
488 " This function is used internally to help with command completion and should.\n"
489 " never be called by the user directly.\n";
491 static char commandmatchesarray_help[] =
492 "Usage: _command matchesarray \"<line>\" text \n"
493 " This function is used internally to help with command completion and should.\n"
494 " never be called by the user directly.\n";
496 static int handle_softhangup(int fd, int argc, char *argv[])
498 struct ast_channel *c=NULL;
500 return RESULT_SHOWUSAGE;
501 c = ast_get_channel_by_name_locked(argv[2]);
503 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
504 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
505 ast_mutex_unlock(&c->lock);
507 ast_cli(fd, "%s is not a known channel\n", argv[2]);
508 return RESULT_SUCCESS;
511 static char *__ast_cli_generator(char *text, char *word, int state, int lock);
513 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
522 return RESULT_SHOWUSAGE;
523 buf = malloc(buflen);
525 return RESULT_FAILURE;
527 matches = ast_cli_completion_matches(argv[2], argv[3]);
529 for (x=0; matches[x]; x++) {
531 printf("command matchesarray for '%s' %s got '%s'\n", argv[2], argv[3], matches[x]);
533 matchlen = strlen(matches[x]) + 1;
534 if (len + matchlen >= buflen) {
535 buflen += matchlen * 3;
537 buf = realloc(obuf, buflen);
539 /* Out of memory... Just free old buffer and be done */
543 len += sprintf( buf + len, "%s ", matches[x]);
550 printf("array for '%s' %s got '%s'\n", argv[2], argv[3], buf);
554 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
557 ast_cli(fd, "NULL\n");
559 return RESULT_SUCCESS;
564 static int handle_commandnummatches(int fd, int argc, char *argv[])
569 return RESULT_SHOWUSAGE;
571 matches = ast_cli_generatornummatches(argv[2], argv[3]);
574 printf("Search for '%s' %s got '%d'\n", argv[2], argv[3], matches);
576 ast_cli(fd, "%d", matches);
578 return RESULT_SUCCESS;
581 static int handle_commandcomplete(int fd, int argc, char *argv[])
585 printf("Search for %d args: '%s', '%s', '%s', '%s'\n", argc, argv[0], argv[1], argv[2], argv[3]);
588 return RESULT_SHOWUSAGE;
589 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
591 printf("Search for '%s' %s %d got '%s'\n", argv[2], argv[3], atoi(argv[4]), buf);
597 ast_cli(fd, "NULL\n");
598 return RESULT_SUCCESS;
601 static int handle_debuglevel(int fd, int argc, char *argv[])
604 char *filename = "<any>";
605 if ((argc < 3) || (argc > 4))
606 return RESULT_SHOWUSAGE;
607 if (sscanf(argv[2], "%d", &newlevel) != 1)
608 return RESULT_SHOWUSAGE;
609 option_debug = newlevel;
612 ast_copy_string(debug_filename, filename, sizeof(debug_filename));
614 debug_filename[0] = '\0';
616 ast_cli(fd, "Debugging level set to %d, file '%s'\n", newlevel, filename);
617 return RESULT_SUCCESS;
620 #define DEBUGCHAN_FLAG 0x80000000
621 /* XXX todo: merge next two functions!!! */
622 static int handle_debugchan(int fd, int argc, char *argv[])
624 struct ast_channel *c=NULL;
627 return RESULT_SHOWUSAGE;
629 is_all = !strcasecmp("all", argv[2]);
631 global_fin |= DEBUGCHAN_FLAG;
632 global_fout |= DEBUGCHAN_FLAG;
633 c = ast_channel_walk_locked(NULL);
635 c = ast_get_channel_by_name_locked(argv[2]);
637 ast_cli(fd, "No such channel %s\n", argv[2]);
640 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
641 c->fin |= DEBUGCHAN_FLAG;
642 c->fout |= DEBUGCHAN_FLAG;
643 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
645 ast_mutex_unlock(&c->lock);
648 c = ast_channel_walk_locked(c);
650 ast_cli(fd, "Debugging on new channels is enabled\n");
651 return RESULT_SUCCESS;
654 static int handle_nodebugchan(int fd, int argc, char *argv[])
656 struct ast_channel *c=NULL;
659 return RESULT_SHOWUSAGE;
660 is_all = !strcasecmp("all", argv[3]);
662 global_fin &= ~DEBUGCHAN_FLAG;
663 global_fout &= ~DEBUGCHAN_FLAG;
664 c = ast_channel_walk_locked(NULL);
666 c = ast_get_channel_by_name_locked(argv[3]);
668 ast_cli(fd, "No such channel %s\n", argv[3]);
671 if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
672 c->fin &= ~DEBUGCHAN_FLAG;
673 c->fout &= ~DEBUGCHAN_FLAG;
674 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
676 ast_mutex_unlock(&c->lock);
679 c = ast_channel_walk_locked(c);
681 ast_cli(fd, "Debugging on new channels is disabled\n");
682 return RESULT_SUCCESS;
687 static int handle_showchan(int fd, int argc, char *argv[])
689 struct ast_channel *c=NULL;
693 char nf[256], wf[256], rf[256];
694 long elapsed_seconds=0;
695 int hour=0, min=0, sec=0;
698 return RESULT_SHOWUSAGE;
700 c = ast_get_channel_by_name_locked(argv[2]);
702 ast_cli(fd, "%s is not a known channel\n", argv[2]);
703 return RESULT_SUCCESS;
706 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
707 hour = elapsed_seconds / 3600;
708 min = (elapsed_seconds % 3600) / 60;
709 sec = elapsed_seconds % 60;
710 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
712 strcpy(cdrtime, "N/A");
719 " Caller ID Name: %s\n"
723 " NativeFormats: %s\n"
726 "1st File Descriptor: %d\n"
728 " Frames out: %d%s\n"
729 " Time to Hangup: %ld\n"
730 " Elapsed Time: %s\n"
731 " Direct Bridge: %s\n"
732 "Indirect Bridge: %s\n"
738 " Pickup Group: %d\n"
741 " Blocking in: %s\n",
742 c->name, c->type, c->uniqueid,
743 (c->cid.cid_num ? c->cid.cid_num : "(N/A)"),
744 (c->cid.cid_name ? c->cid.cid_name : "(N/A)"),
745 (c->cid.cid_dnid ? c->cid.cid_dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings,
746 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
747 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
748 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
749 c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
750 c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", (long)c->whentohangup,
751 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
752 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
753 ( c-> data ? (!ast_strlen_zero(c->data) ? c->data : "(Empty)") : "(None)"),
754 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
756 if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
757 ast_cli(fd," Variables:\n%s\n",buf);
758 if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
759 ast_cli(fd," CDR Variables:\n%s\n",buf);
761 ast_mutex_unlock(&c->lock);
762 return RESULT_SUCCESS;
765 static char *complete_show_channels(char *line, char *word, int pos, int state)
767 static char *choices[] = { "concise", "verbose" };
775 wordlen = strlen(word);
777 for (x = 0; x < sizeof(choices) / sizeof(choices[0]); x++) {
778 if (!strncasecmp(word, choices[x], wordlen)) {
781 return strdup(choices[x]);
788 static char *complete_ch_helper(char *line, char *word, int pos, int state, int rpos)
790 struct ast_channel *c = NULL;
798 wordlen = strlen(word);
800 while ((c = ast_channel_walk_locked(c))) {
801 if (!strncasecmp(word, c->name, wordlen)) {
802 if (++which > state) {
803 ret = strdup(c->name);
804 ast_mutex_unlock(&c->lock);
808 ast_mutex_unlock(&c->lock);
814 static char *complete_ch_3(char *line, char *word, int pos, int state)
816 return complete_ch_helper(line, word, pos, state, 2);
819 static char *complete_ch_4(char *line, char *word, int pos, int state)
821 return complete_ch_helper(line, word, pos, state, 3);
824 static char *complete_mod_2(char *line, char *word, int pos, int state)
826 return ast_module_helper(line, word, pos, state, 1, 1);
829 static char *complete_mod_4(char *line, char *word, int pos, int state)
831 return ast_module_helper(line, word, pos, state, 3, 0);
834 static char *complete_fn(char *line, char *word, int pos, int state)
843 ast_copy_string(filename, word, sizeof(filename));
845 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
847 c = filename_completion_function(filename, state);
849 if (c && word[0] != '/')
850 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
852 return c ? strdup(c) : c;
855 static int group_show_channels(int fd, int argc, char *argv[])
857 #define FORMAT_STRING "%-25s %-20s %-20s\n"
859 struct ast_channel *c = NULL;
861 struct ast_var_t *current;
862 struct varshead *headp;
866 if (argc < 3 || argc > 4)
867 return RESULT_SHOWUSAGE;
870 if (regcomp(®exbuf, argv[3], REG_EXTENDED | REG_NOSUB))
871 return RESULT_SHOWUSAGE;
875 ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
876 while ( (c = ast_channel_walk_locked(c)) != NULL) {
878 AST_LIST_TRAVERSE(headp,current,entries) {
879 if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
880 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
881 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
882 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
885 } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
886 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
887 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
893 ast_mutex_unlock(&c->lock);
899 ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
900 return RESULT_SUCCESS;
904 static int handle_help(int fd, int argc, char *argv[]);
906 static char * complete_help(char *text, char *word, int pos, int state)
908 /* skip first 4 or 5 chars, "help "*/
909 int l = strlen(text);
915 /* XXX watch out, should stop to the non-generator parts */
916 return __ast_cli_generator(text, word, state, 0); /* Don't lock as we are already locked */
919 static struct ast_cli_entry builtins[] = {
920 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
921 { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
922 { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
923 { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
924 { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch_3 },
925 { { "debug", "level", NULL }, handle_debuglevel, "Set global debug level", debuglevel_help },
926 { { "group", "show", "channels", NULL }, group_show_channels, "Show active channels with group(s)", group_show_channels_help},
927 { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help, complete_help },
928 { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
929 { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch_4 },
930 { { "reload", NULL }, handle_reload, "Reload configuration", reload_help, complete_mod_2 },
931 { { "set", "debug", NULL }, handle_set_debug, "Set level of debug chattiness", set_debug_help },
932 { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
933 { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch_3 },
934 { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help, complete_show_channels },
935 { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
936 { { "show", "modules", "like", NULL }, handle_modlist, "List modules and info", modlist_help, complete_mod_4 },
937 { { "show", "uptime", NULL }, handle_showuptime, "Show uptime information", uptime_help },
938 { { "show", "version", NULL }, handle_version, "Display version info", version_help },
939 { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch_3 },
940 { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
941 { { NULL }, NULL, NULL, NULL }
944 static struct ast_cli_entry *find_cli(char *cmds[], int exact)
949 struct ast_cli_entry *e=NULL;
951 for (e=helpers;e;e=e->next) {
953 for (y=0;match && cmds[y]; y++) {
954 if (!e->cmda[y] && !exact)
956 if (!e->cmda[y] || strcasecmp(e->cmda[y], cmds[y]))
959 if ((exact > -1) && e->cmda[y])
966 for (x=0;builtins[x].cmda[0];x++) {
967 /* start optimistic */
969 for (y=0;match && cmds[y]; y++) {
970 /* If there are no more words in the candidate command, then we're
972 if (!builtins[x].cmda[y] && !exact)
974 /* If there are no more words in the command (and we're looking for
975 an exact match) or there is a difference between the two words,
976 then this is not a match */
977 if (!builtins[x].cmda[y] || strcasecmp(builtins[x].cmda[y], cmds[y]))
980 /* If more words are needed to complete the command then this is not
981 a candidate (unless we're looking for a really inexact answer */
982 if ((exact > -1) && builtins[x].cmda[y])
990 static void join(char *dest, size_t destsize, char *w[], int tws)
992 ast_join(dest, destsize, w);
994 if (tws && !ast_strlen_zero(dest))
995 strncat(dest, " ", destsize - strlen(dest) - 1);
998 static void join2(char *dest, size_t destsize, char *w[])
1001 /* Join words into a string */
1002 if (!dest || destsize < 1) {
1006 for (x=0;w[x];x++) {
1007 strncat(dest, w[x], destsize - strlen(dest) - 1);
1011 static char *find_best(char *argv[])
1013 static char cmdline[80];
1015 /* See how close we get, then print the */
1016 char *myargv[AST_MAX_CMD_LEN];
1017 for (x=0;x<AST_MAX_CMD_LEN;x++)
1019 for (x=0;argv[x];x++) {
1020 myargv[x] = argv[x];
1021 if (!find_cli(myargv, -1))
1024 join(cmdline, sizeof(cmdline), myargv, 0);
1028 int ast_cli_unregister(struct ast_cli_entry *e)
1030 struct ast_cli_entry *cur, *l=NULL;
1031 ast_mutex_lock(&clilock);
1036 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1050 ast_mutex_unlock(&clilock);
1054 int ast_cli_register(struct ast_cli_entry *e)
1056 struct ast_cli_entry *cur, *l=NULL;
1057 char fulle[80] ="", fulltst[80] ="";
1060 ast_mutex_lock(&clilock);
1061 join2(fulle, sizeof(fulle), e->cmda);
1063 if (find_cli(e->cmda, -1)) {
1064 ast_mutex_unlock(&clilock);
1065 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1069 for (cur = helpers; cur; cur = cur->next) {
1070 join2(fulltst, sizeof(fulltst), cur->cmda);
1071 len = strlen(fulltst);
1072 if (strlen(fulle) < len)
1073 len = strlen(fulle);
1074 if (strncasecmp(fulle, fulltst, len) < 0) {
1095 ast_mutex_unlock(&clilock);
1101 * register/unregister an array of entries.
1103 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1107 for (i = 0; i < len; i++)
1108 ast_cli_register(e + i);
1111 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1115 for (i = 0; i < len; i++)
1116 ast_cli_unregister(e + i);
1119 static int help_workhorse(int fd, char *match[])
1121 char fullcmd1[80] = "";
1122 char fullcmd2[80] = "";
1124 char *fullcmd = NULL;
1125 struct ast_cli_entry *e, *e1, *e2;
1129 join(matchstr, sizeof(matchstr), match, 0);
1130 while(e1->cmda[0] || e2) {
1132 join(fullcmd2, sizeof(fullcmd2), e2->cmda, 0);
1134 join(fullcmd1, sizeof(fullcmd1), e1->cmda, 0);
1136 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
1140 /* Increment by going to next */
1148 /* Hide commands that start with '_' */
1149 if (fullcmd[0] == '_')
1152 if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1156 ast_cli(fd, "%25.25s %s\n", fullcmd, e->summary);
1161 static int handle_help(int fd, int argc, char *argv[]) {
1162 struct ast_cli_entry *e;
1165 return RESULT_SHOWUSAGE;
1167 e = find_cli(argv + 1, 1);
1170 ast_cli(fd, "%s", e->usage);
1172 join(fullcmd, sizeof(fullcmd), argv+1, 0);
1173 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1176 if (find_cli(argv + 1, -1)) {
1177 return help_workhorse(fd, argv + 1);
1179 join(fullcmd, sizeof(fullcmd), argv+1, 0);
1180 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1184 return help_workhorse(fd, NULL);
1186 return RESULT_SUCCESS;
1189 static char *parse_args(char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1197 *trailingwhitespace = 0;
1198 if (!(dup = strdup(s)))
1202 while (!ast_strlen_zero(s)) {
1203 if ((*s == '"') && !escaped) {
1205 if (quoted & whitespace) {
1206 /* If we're starting a quoted string, coming off white space, start a new argument */
1207 if (x >= (max - 1)) {
1208 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1215 } else if (((*s == ' ') || (*s == '\t')) && !(quoted || escaped)) {
1216 /* If we are not already in whitespace, and not in a quoted string or
1217 processing an escape sequence, and just entered whitespace, then
1218 finalize the previous argument and remember that we are in whitespace
1224 } else if ((*s == '\\') && !escaped) {
1228 /* If we are coming out of whitespace, start a new argument */
1229 if (x >= (max - 1)) {
1230 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1241 /* Null terminate */
1245 *trailingwhitespace = whitespace;
1249 /* This returns the number of unique matches for the generator */
1250 int ast_cli_generatornummatches(char *text, char *word)
1252 int matches = 0, i = 0;
1253 char *buf = NULL, *oldbuf = NULL;
1255 while ((buf = ast_cli_generator(text, word, i++))) {
1256 if (!oldbuf || strcmp(buf,oldbuf))
1267 char **ast_cli_completion_matches(char *text, char *word)
1269 char **match_list = NULL, *retstr, *prevstr;
1270 size_t match_list_len, max_equal, which, i;
1274 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1275 if (matches + 1 >= match_list_len) {
1276 match_list_len <<= 1;
1277 match_list = realloc(match_list, match_list_len * sizeof(char *));
1279 match_list[++matches] = retstr;
1283 return (char **) NULL;
1286 prevstr = match_list[1];
1287 max_equal = strlen(prevstr);
1288 for (; which <= matches; which++) {
1289 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1294 retstr = malloc(max_equal + 1);
1295 strncpy(retstr, match_list[1], max_equal);
1296 retstr[max_equal] = '\0';
1297 match_list[0] = retstr;
1299 if (matches + 1 >= match_list_len)
1300 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1301 match_list[matches + 1] = (char *) NULL;
1306 static char *__ast_cli_generator(char *text, char *word, int state, int lock)
1308 char *argv[AST_MAX_ARGS];
1309 struct ast_cli_entry *e, *e1, *e2;
1313 char fullcmd1[80] = "";
1314 char fullcmd2[80] = "";
1315 char matchstr[80] = "";
1316 char *fullcmd = NULL;
1319 if ((dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws))) {
1320 join(matchstr, sizeof(matchstr), argv, tws);
1322 ast_mutex_lock(&clilock);
1325 while(e1->cmda[0] || e2) {
1327 join(fullcmd2, sizeof(fullcmd2), e2->cmda, tws);
1329 join(fullcmd1, sizeof(fullcmd1), e1->cmda, tws);
1331 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
1335 /* Increment by going to next */
1343 if ((fullcmd[0] != '_') && !strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1344 /* We contain the first part of one or more commands */
1345 /* Now, what we're supposed to return is the next word... */
1346 if (!ast_strlen_zero(word) && x>0) {
1353 if (matchnum > state) {
1355 ast_mutex_unlock(&clilock);
1361 if (e->generator && !strncasecmp(matchstr, fullcmd, strlen(fullcmd)) &&
1362 (matchstr[strlen(fullcmd)] < 33)) {
1363 /* We have a command in its entirity within us -- theoretically only one
1364 command can have this occur */
1365 fullcmd = e->generator(matchstr, word, (!ast_strlen_zero(word) ? (x - 1) : (x)), state);
1368 ast_mutex_unlock(&clilock);
1376 ast_mutex_unlock(&clilock);
1382 char *ast_cli_generator(char *text, char *word, int state)
1384 return __ast_cli_generator(text, word, state, 1);
1387 int ast_cli_command(int fd, char *s)
1389 char *argv[AST_MAX_ARGS];
1390 struct ast_cli_entry *e;
1395 dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1397 ast_log(LOG_ERROR, "Out of Memory!\n");
1401 /* We need at least one entry, or ignore */
1403 ast_mutex_lock(&clilock);
1404 e = find_cli(argv, 0);
1407 ast_mutex_unlock(&clilock);
1409 switch(e->handler(fd, x, argv)) {
1410 case RESULT_SHOWUSAGE:
1411 ast_cli(fd, "%s", e->usage);
1415 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1417 ast_mutex_lock(&clilock);
1419 ast_mutex_unlock(&clilock);