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 #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/linkedlists.h"
44 #include "asterisk/module.h"
45 #include "asterisk/pbx.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/manager.h"
48 #include "asterisk/utils.h"
49 #include "asterisk/app.h"
50 #include "asterisk/lock.h"
51 /* For rl_filename_completion */
52 #include "editline/readline/readline.h"
53 /* For module directory */
54 #include "asterisk/version.h"
56 extern const char *ast_build_hostname;
57 extern const char *ast_build_kernel;
58 extern const char *ast_build_machine;
59 extern const char *ast_build_os;
60 extern const char *ast_build_date;
61 extern const char *ast_build_user;
63 extern unsigned long global_fin, global_fout;
65 void ast_cli(int fd, char *fmt, ...)
72 res = vasprintf(&stuff, fmt, ap);
75 ast_log(LOG_ERROR, "Memory allocation failure\n");
77 ast_carefulwrite(fd, stuff, strlen(stuff), 100);
82 static AST_LIST_HEAD_STATIC(helpers, ast_cli_entry);
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 char frog_help[] =
138 "Usage: frog [warp_factor]\n"
139 " Performs frog-in-a-blender calculations (Jacobsen Corollary)\n";
141 static int handle_load(int fd, int argc, char *argv[])
144 return RESULT_SHOWUSAGE;
145 if (ast_load_resource(argv[1])) {
146 ast_cli(fd, "Unable to load module %s\n", argv[1]);
147 return RESULT_FAILURE;
149 return RESULT_SUCCESS;
152 static int handle_reload(int fd, int argc, char *argv[])
157 return RESULT_SHOWUSAGE;
159 for (x=1;x<argc;x++) {
160 res = ast_module_reload(argv[x]);
163 ast_cli(fd, "No such module '%s'\n", argv[x]);
166 ast_cli(fd, "Module '%s' does not support reload\n", argv[x]);
171 ast_module_reload(NULL);
172 return RESULT_SUCCESS;
175 static int handle_set_verbose(int fd, int argc, char *argv[])
178 int oldval = option_verbose;
180 /* "set verbose [atleast] N" */
182 option_verbose = atoi(argv[2]);
183 else if (argc == 4) {
184 if (strcasecmp(argv[2], "atleast"))
185 return RESULT_SHOWUSAGE;
187 if (val > option_verbose)
188 option_verbose = val;
190 return RESULT_SHOWUSAGE;
191 if (oldval != option_verbose && option_verbose > 0)
192 ast_cli(fd, "Verbosity was %d and is now %d\n", oldval, option_verbose);
193 else if (oldval > 0 && option_verbose > 0)
194 ast_cli(fd, "Verbosity is at least %d\n", option_verbose);
195 else if (oldval > 0 && option_verbose == 0)
196 ast_cli(fd, "Verbosity is now OFF\n");
197 return RESULT_SUCCESS;
200 static int handle_set_debug(int fd, int argc, char *argv[])
203 int oldval = option_debug;
205 /* "set debug [atleast] N" */
207 option_debug = atoi(argv[2]);
208 else if (argc == 4) {
209 if (strcasecmp(argv[2], "atleast"))
210 return RESULT_SHOWUSAGE;
212 if (val > option_debug)
215 return RESULT_SHOWUSAGE;
216 if (oldval != option_debug && option_debug > 0)
217 ast_cli(fd, "Core debug was %d and is now %d\n", oldval, option_debug);
218 else if (oldval > 0 && option_debug > 0)
219 ast_cli(fd, "Core debug is at least %d\n", option_debug);
220 else if (oldval > 0 && option_debug == 0)
221 ast_cli(fd, "Core debug is now OFF\n");
222 return RESULT_SUCCESS;
225 static int handle_unload(int fd, int argc, char *argv[])
228 int force=AST_FORCE_SOFT;
230 return RESULT_SHOWUSAGE;
231 for (x=1;x<argc;x++) {
232 if (argv[x][0] == '-') {
235 force = AST_FORCE_FIRM;
238 force = AST_FORCE_HARD;
241 return RESULT_SHOWUSAGE;
243 } else if (x != argc - 1)
244 return RESULT_SHOWUSAGE;
245 else if (ast_unload_resource(argv[x], force)) {
246 ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
247 return RESULT_FAILURE;
250 return RESULT_SUCCESS;
254 * Perform frong-in-a-blender calculations (Jacobsen Corollary)
257 static int handle_frog(int fd, int argc, char *argv[])
259 double warpone = 75139293848.0;
260 double warpfactor = 1.0;
263 return RESULT_SHOWUSAGE;
264 if (argc > 1 && sscanf(argv[1], "%lf", &warpfactor) != 1)
265 return RESULT_SHOWUSAGE;
267 ast_cli(fd, "A frog in a blender with a base diameter of 3 inches going\n");
268 ast_cli(fd, "%.0f RPM will be travelling at warp factor %f,\n",
269 warpfactor * warpfactor * warpfactor * warpone, warpfactor);
270 ast_cli(fd, "based upon the Jacobsen Frog Corollary.\n");
271 return RESULT_SUCCESS;
275 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
276 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
278 AST_MUTEX_DEFINE_STATIC(climodentrylock);
279 static int climodentryfd = -1;
281 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
283 /* Comparing the like with the module */
284 if (strcasestr(module, like) ) {
285 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
291 static char modlist_help[] =
292 "Usage: show modules [like keyword]\n"
293 " Shows Asterisk modules currently in use, and usage statistics.\n";
295 static char version_help[] =
296 "Usage: show version\n"
297 " Shows Asterisk version information.\n";
299 static char uptime_help[] =
300 "Usage: show uptime [seconds]\n"
301 " Shows Asterisk uptime information.\n"
302 " The seconds word returns the uptime in seconds only.\n";
304 static void print_uptimestr(int fd, time_t timeval, const char *prefix, int printsec)
306 int x; /* the main part - years, weeks, etc. */
307 char timestr[256]="", *s = timestr;
308 size_t maxbytes = sizeof(timestr);
311 #define MINUTE (SECOND*60)
312 #define HOUR (MINUTE*60)
313 #define DAY (HOUR*24)
315 #define YEAR (DAY*365)
316 #define ESS(x) ((x == 1) ? "" : "s") /* plural suffix */
317 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
318 if (timeval < 0) /* invalid, nothing to show */
320 if (printsec) { /* plain seconds output */
321 ast_build_string(&s, &maxbytes, "%lu", (u_long)timeval);
322 timeval = 0; /* bypass the other cases */
324 if (timeval > YEAR) {
325 x = (timeval / YEAR);
326 timeval -= (x * YEAR);
327 ast_build_string(&s, &maxbytes, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval));
329 if (timeval > WEEK) {
330 x = (timeval / WEEK);
331 timeval -= (x * WEEK);
332 ast_build_string(&s, &maxbytes, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval));
336 timeval -= (x * DAY);
337 ast_build_string(&s, &maxbytes, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval));
339 if (timeval > HOUR) {
340 x = (timeval / HOUR);
341 timeval -= (x * HOUR);
342 ast_build_string(&s, &maxbytes, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval));
344 if (timeval > MINUTE) {
345 x = (timeval / MINUTE);
346 timeval -= (x * MINUTE);
347 ast_build_string(&s, &maxbytes, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval));
351 ast_build_string(&s, &maxbytes, "%d second%s ", x, ESS(x));
352 if (timestr[0] != '\0')
353 ast_cli(fd, "%s: %s\n", prefix, timestr);
356 static int handle_showuptime(int fd, int argc, char *argv[])
358 /* 'show uptime [seconds]' */
359 time_t curtime = time(NULL);
360 int printsec = (argc == 3 && !strcasecmp(argv[2],"seconds"));
362 if (argc != 2 && !printsec)
363 return RESULT_SHOWUSAGE;
365 print_uptimestr(fd, curtime - ast_startuptime, "System uptime", printsec);
366 if (ast_lastreloadtime)
367 print_uptimestr(fd, curtime - ast_lastreloadtime, "Last reload", printsec);
368 return RESULT_SUCCESS;
371 static int handle_modlist(int fd, int argc, char *argv[])
375 return RESULT_SHOWUSAGE;
376 else if (argc >= 4) {
377 if (strcmp(argv[2],"like"))
378 return RESULT_SHOWUSAGE;
382 ast_mutex_lock(&climodentrylock);
383 climodentryfd = fd; /* global, protected by climodentrylock */
384 ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
385 ast_cli(fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
387 ast_mutex_unlock(&climodentrylock);
388 return RESULT_SUCCESS;
390 #undef MODLIST_FORMAT
391 #undef MODLIST_FORMAT2
393 static int handle_version(int fd, int argc, char *argv[])
396 return RESULT_SHOWUSAGE;
397 ast_cli(fd, "Asterisk %s built by %s @ %s on a %s running %s on %s\n",
398 ASTERISK_VERSION, ast_build_user, ast_build_hostname,
399 ast_build_machine, ast_build_os, ast_build_date);
400 return RESULT_SUCCESS;
403 static int handle_chanlist(int fd, int argc, char *argv[])
405 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
406 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
407 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s\n"
408 #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"
409 #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"
411 struct ast_channel *c = NULL;
412 char durbuf[10] = "-";
416 int durh, durm, durs;
417 int numchans = 0, concise = 0, verbose = 0;
419 concise = (argc == 3 && (!strcasecmp(argv[2],"concise")));
420 verbose = (argc == 3 && (!strcasecmp(argv[2],"verbose")));
422 if (argc < 2 || argc > 3 || (argc == 3 && !concise && !verbose))
423 return RESULT_SHOWUSAGE;
425 if (!concise && !verbose)
426 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
428 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
429 "CallerID", "Duration", "Accountcode", "BridgedTo");
431 while ((c = ast_channel_walk_locked(c)) != NULL) {
432 struct ast_channel *bc = ast_bridged_channel(c);
433 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
434 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
436 durh = duration / 3600;
437 durm = (duration % 3600) / 60;
438 durs = duration % 60;
439 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
441 snprintf(durbuf, sizeof(durbuf), "%d", duration);
447 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
448 c->appl ? c->appl : "(None)", c->data ? c->data : "",
449 S_OR(c->cid.cid_num, ""),
450 c->accountcode ? c->accountcode : "", c->amaflags,
451 durbuf, 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)", c->data ? S_OR(c->data, "(Empty)" ): "(None)",
455 S_OR(c->cid.cid_num, ""), durbuf,
456 c->accountcode ? c->accountcode : "", bc ? bc->name : "(None)");
458 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
459 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
461 strcpy(locbuf, "(None)");
463 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, c->data ? c->data : "");
465 strcpy(appdata, "(None)");
466 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
469 ast_mutex_unlock(&c->lock);
472 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
474 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
475 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
476 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
478 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
480 return RESULT_SUCCESS;
483 #undef FORMAT_STRING2
484 #undef CONCISE_FORMAT_STRING
485 #undef VERBOSE_FORMAT_STRING
486 #undef VERBOSE_FORMAT_STRING2
489 static char showchan_help[] =
490 "Usage: show channel <channel>\n"
491 " Shows lots of information about the specified channel.\n";
493 static char debugchan_help[] =
494 "Usage: debug channel <channel>\n"
495 " Enables debugging on a specific channel.\n";
497 static char debuglevel_help[] =
498 "Usage: debug level <level> [filename]\n"
499 " Set debug to specified level (0 to disable). If filename\n"
500 "is specified, debugging will be limited to just that file.\n";
502 static char nodebugchan_help[] =
503 "Usage: no debug channel <channel>\n"
504 " Disables debugging on a specific channel.\n";
506 static char commandcomplete_help[] =
507 "Usage: _command complete \"<line>\" text state\n"
508 " This function is used internally to help with command completion and should.\n"
509 " never be called by the user directly.\n";
511 static char commandnummatches_help[] =
512 "Usage: _command nummatches \"<line>\" text \n"
513 " This function is used internally to help with command completion and should.\n"
514 " never be called by the user directly.\n";
516 static char commandmatchesarray_help[] =
517 "Usage: _command matchesarray \"<line>\" text \n"
518 " This function is used internally to help with command completion and should.\n"
519 " never be called by the user directly.\n";
521 static int handle_softhangup(int fd, int argc, char *argv[])
523 struct ast_channel *c=NULL;
525 return RESULT_SHOWUSAGE;
526 c = ast_get_channel_by_name_locked(argv[2]);
528 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
529 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
530 ast_mutex_unlock(&c->lock);
532 ast_cli(fd, "%s is not a known channel\n", argv[2]);
533 return RESULT_SUCCESS;
536 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
538 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
547 return RESULT_SHOWUSAGE;
548 if (!(buf = ast_malloc(buflen)))
549 return RESULT_FAILURE;
551 matches = ast_cli_completion_matches(argv[2], argv[3]);
553 for (x=0; matches[x]; x++) {
554 matchlen = strlen(matches[x]) + 1;
555 if (len + matchlen >= buflen) {
556 buflen += matchlen * 3;
558 if (!(buf = ast_realloc(obuf, buflen)))
559 /* Memory allocation failure... Just free old buffer and be done */
563 len += sprintf( buf + len, "%s ", matches[x]);
571 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
574 ast_cli(fd, "NULL\n");
576 return RESULT_SUCCESS;
581 static int handle_commandnummatches(int fd, int argc, char *argv[])
586 return RESULT_SHOWUSAGE;
588 matches = ast_cli_generatornummatches(argv[2], argv[3]);
590 ast_cli(fd, "%d", matches);
592 return RESULT_SUCCESS;
595 static int handle_commandcomplete(int fd, int argc, char *argv[])
600 return RESULT_SHOWUSAGE;
601 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
606 ast_cli(fd, "NULL\n");
607 return RESULT_SUCCESS;
610 static int handle_debuglevel(int fd, int argc, char *argv[])
613 char *filename = "<any>";
614 if ((argc < 3) || (argc > 4))
615 return RESULT_SHOWUSAGE;
616 if (sscanf(argv[2], "%d", &newlevel) != 1)
617 return RESULT_SHOWUSAGE;
618 option_debug = newlevel;
621 ast_copy_string(debug_filename, filename, sizeof(debug_filename));
623 debug_filename[0] = '\0';
625 ast_cli(fd, "Debugging level set to %d, file '%s'\n", newlevel, filename);
626 return RESULT_SUCCESS;
629 #define DEBUGCHAN_FLAG 0x80000000
630 /* XXX todo: merge next two functions!!! */
631 static int handle_debugchan(int fd, int argc, char *argv[])
633 struct ast_channel *c=NULL;
636 /* 'debug channel {all|chan_id}' */
638 return RESULT_SHOWUSAGE;
640 is_all = !strcasecmp("all", argv[2]);
642 global_fin |= DEBUGCHAN_FLAG;
643 global_fout |= DEBUGCHAN_FLAG;
644 c = ast_channel_walk_locked(NULL);
646 c = ast_get_channel_by_name_locked(argv[2]);
648 ast_cli(fd, "No such channel %s\n", argv[2]);
651 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
652 c->fin |= DEBUGCHAN_FLAG;
653 c->fout |= DEBUGCHAN_FLAG;
654 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
656 ast_mutex_unlock(&c->lock);
659 c = ast_channel_walk_locked(c);
661 ast_cli(fd, "Debugging on new channels is enabled\n");
662 return RESULT_SUCCESS;
665 static int handle_nodebugchan(int fd, int argc, char *argv[])
667 struct ast_channel *c=NULL;
669 /* 'no debug channel {all|chan_id}' */
671 return RESULT_SHOWUSAGE;
672 is_all = !strcasecmp("all", argv[3]);
674 global_fin &= ~DEBUGCHAN_FLAG;
675 global_fout &= ~DEBUGCHAN_FLAG;
676 c = ast_channel_walk_locked(NULL);
678 c = ast_get_channel_by_name_locked(argv[3]);
680 ast_cli(fd, "No such channel %s\n", argv[3]);
683 if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
684 c->fin &= ~DEBUGCHAN_FLAG;
685 c->fout &= ~DEBUGCHAN_FLAG;
686 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
688 ast_mutex_unlock(&c->lock);
691 c = ast_channel_walk_locked(c);
693 ast_cli(fd, "Debugging on new channels is disabled\n");
694 return RESULT_SUCCESS;
697 static int handle_showchan(int fd, int argc, char *argv[])
699 struct ast_channel *c=NULL;
703 char nf[256], wf[256], rf[256];
704 long elapsed_seconds=0;
705 int hour=0, min=0, sec=0;
708 return RESULT_SHOWUSAGE;
710 c = ast_get_channel_by_name_locked(argv[2]);
712 ast_cli(fd, "%s is not a known channel\n", argv[2]);
713 return RESULT_SUCCESS;
716 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
717 hour = elapsed_seconds / 3600;
718 min = (elapsed_seconds % 3600) / 60;
719 sec = elapsed_seconds % 60;
720 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
722 strcpy(cdrtime, "N/A");
729 " Caller ID Name: %s\n"
733 " NativeFormats: %s\n"
736 "1st File Descriptor: %d\n"
738 " Frames out: %d%s\n"
739 " Time to Hangup: %ld\n"
740 " Elapsed Time: %s\n"
741 " Direct Bridge: %s\n"
742 "Indirect Bridge: %s\n"
748 " Pickup Group: %d\n"
751 " Blocking in: %s\n",
752 c->name, c->tech->type, c->uniqueid,
753 S_OR(c->cid.cid_num, "(N/A)"),
754 S_OR(c->cid.cid_name, "(N/A)"),
755 S_OR(c->cid.cid_dnid, "(N/A)"), ast_state2str(c->_state), c->_state, c->rings,
756 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
757 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
758 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
759 c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
760 c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", (long)c->whentohangup,
761 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
762 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
763 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
764 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
766 if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
767 ast_cli(fd," Variables:\n%s\n",buf);
768 if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
769 ast_cli(fd," CDR Variables:\n%s\n",buf);
771 ast_mutex_unlock(&c->lock);
772 return RESULT_SUCCESS;
776 * helper function to generate CLI matches from a fixed set of values.
777 * A NULL word is acceptable.
779 char *ast_cli_complete(const char *word, char *const choices[], int state)
781 int i, which = 0, len;
782 len = ast_strlen_zero(word) ? 0 : strlen(word);
784 for (i = 0; choices[i]; i++) {
785 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
786 return ast_strdup(choices[i]);
791 static char *complete_show_channels(const char *line, const char *word, int pos, int state)
793 static char *choices[] = { "concise", "verbose", NULL };
795 return (pos != 2) ? NULL : ast_cli_complete(word, choices, state);
798 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
800 struct ast_channel *c = NULL;
803 char notfound = '\0';
804 char *ret = ¬found; /* so NULL can break the loop */
809 wordlen = strlen(word);
811 while (ret == ¬found && (c = ast_channel_walk_locked(c))) {
812 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
813 ret = ast_strdup(c->name);
814 ast_mutex_unlock(&c->lock);
816 return ret == ¬found ? NULL : ret;
819 static char *complete_ch_3(const char *line, const char *word, int pos, int state)
821 return ast_complete_channels(line, word, pos, state, 2);
824 static char *complete_ch_4(const char *line, const char *word, int pos, int state)
826 return ast_complete_channels(line, word, pos, state, 3);
829 static char *complete_mod_2(const char *line, const char *word, int pos, int state)
831 return ast_module_helper(line, word, pos, state, 1, 1);
834 static char *complete_mod_4(const char *line, const char *word, int pos, int state)
836 return ast_module_helper(line, word, pos, state, 3, 0);
839 static char *complete_fn(const char *line, const char *word, int pos, int state)
848 ast_copy_string(filename, word, sizeof(filename));
850 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
852 c = filename_completion_function(filename, state);
854 if (c && word[0] != '/')
855 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
857 return c ? strdup(c) : c;
860 static int group_show_channels(int fd, int argc, char *argv[])
862 #define FORMAT_STRING "%-25s %-20s %-20s\n"
864 struct ast_channel *c = NULL;
866 struct ast_var_t *current;
867 struct varshead *headp;
871 if (argc < 3 || argc > 4)
872 return RESULT_SHOWUSAGE;
875 if (regcomp(®exbuf, argv[3], REG_EXTENDED | REG_NOSUB))
876 return RESULT_SHOWUSAGE;
880 ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
881 while ( (c = ast_channel_walk_locked(c)) != NULL) {
883 AST_LIST_TRAVERSE(headp,current,entries) {
884 if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
885 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
886 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
887 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
890 } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
891 if (!havepattern || !regexec(®exbuf, ast_var_value(current), 0, NULL, 0)) {
892 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
898 ast_mutex_unlock(&c->lock);
904 ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
905 return RESULT_SUCCESS;
909 static int handle_help(int fd, int argc, char *argv[]);
911 static char * complete_help(const char *text, const char *word, int pos, int state)
913 /* skip first 4 or 5 chars, "help "*/
914 int l = strlen(text);
919 /* XXX watch out, should stop to the non-generator parts */
920 return __ast_cli_generator(text, word, state, 0);
923 static struct ast_cli_entry builtins[] = {
924 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
925 { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
926 { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
927 { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
928 { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch_3 },
929 { { "debug", "level", NULL }, handle_debuglevel, "Set global debug level", debuglevel_help },
930 { { "frog", NULL }, handle_frog,"Perform frog-in-a-blender calculations", frog_help },
931 { { "group", "show", "channels", NULL }, group_show_channels, "Show active channels with group(s)", group_show_channels_help},
932 { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help, complete_help },
933 { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
934 { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch_4 },
935 { { "reload", NULL }, handle_reload, "Reload configuration", reload_help, complete_mod_2 },
936 { { "set", "debug", NULL }, handle_set_debug, "Set level of debug chattiness", set_debug_help },
937 { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
938 { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch_3 },
939 { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help, complete_show_channels },
940 { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
941 { { "show", "modules", "like", NULL }, handle_modlist, "List modules and info", modlist_help, complete_mod_4 },
942 { { "show", "uptime", NULL }, handle_showuptime, "Show uptime information", uptime_help },
943 { { "show", "version", NULL }, handle_version, "Display version info", version_help },
944 { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch_3 },
945 { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
946 { { NULL }, NULL, NULL, NULL }
949 /*! \brief initialize the _full_cmd string in * each of the builtins. */
950 void ast_builtins_init(void)
952 struct ast_cli_entry *e;
954 for (e = builtins; e->cmda[0] != NULL; e++) {
956 ast_join(buf, sizeof(buf), e->cmda);
957 e->_full_cmd = strdup(buf);
959 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
964 * We have two sets of commands: builtins are stored in a
965 * NULL-terminated array of ast_cli_entry, whereas external
966 * commands are in a list.
967 * When navigating, we need to keep two pointers and get
968 * the next one in lexicographic order. For the purpose,
969 * we use a structure.
972 struct cli_iterator {
973 struct ast_cli_entry *builtins;
974 struct ast_cli_entry *helpers;
977 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
979 struct ast_cli_entry *e;
981 if (i->builtins == NULL && i->helpers == NULL) {
983 i->builtins = builtins;
984 i->helpers = AST_LIST_FIRST(&helpers);
986 e = i->builtins; /* temporary */
987 if (!e->cmda[0] || (i->helpers &&
988 strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
992 i->helpers = AST_LIST_NEXT(e, list);
993 } else { /* use builtin. e is already set */
994 (i->builtins)++; /* move to next */
1000 * \brief locate a cli command in the 'helpers' list (which must be locked).
1001 * exact has 3 values:
1002 * 0 returns if the search key is equal or longer than the entry.
1003 * -1 true if the mismatch is on the last word XXX not true!
1004 * 1 true only on complete, exact match.
1006 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1008 int matchlen = -1; /* length of longest match so far */
1009 struct ast_cli_entry *cand = NULL, *e=NULL;
1010 struct cli_iterator i = { NULL, NULL};
1012 while( (e = cli_next(&i)) ) {
1014 for (y = 0 ; cmds[y] && e->cmda[y]; y++) {
1015 if (strcasecmp(e->cmda[y], cmds[y]))
1018 if (e->cmda[y] == NULL) { /* no more words in candidate */
1019 if (cmds[y] == NULL) /* this is an exact match, cannot do better */
1021 /* here the search key is longer than the candidate */
1022 if (match_type != 0) /* but we look for almost exact match... */
1023 continue; /* so we skip this one. */
1024 /* otherwise we like it (case 0) */
1025 } else { /* still words in candidate */
1026 if (cmds[y] == NULL) /* search key is shorter, not good */
1028 /* if we get here, both words exist but there is a mismatch */
1029 if (match_type == 0) /* not the one we look for */
1031 if (match_type == 1) /* not the one we look for */
1033 if (cmds[y+1] != NULL || e->cmda[y+1] != NULL) /* not the one we look for */
1035 /* we are in case match_type == -1 and mismatch on last word */
1037 if (cand == NULL || y > matchlen) /* remember the candidate */
1040 return e ? e : cand;
1043 static char *find_best(char *argv[])
1045 static char cmdline[80];
1047 /* See how close we get, then print the candidate */
1048 char *myargv[AST_MAX_CMD_LEN];
1049 for (x=0;x<AST_MAX_CMD_LEN;x++)
1051 AST_LIST_LOCK(&helpers);
1052 for (x=0;argv[x];x++) {
1053 myargv[x] = argv[x];
1054 if (!find_cli(myargv, -1))
1057 AST_LIST_UNLOCK(&helpers);
1058 ast_join(cmdline, sizeof(cmdline), myargv);
1062 int ast_cli_unregister(struct ast_cli_entry *e)
1065 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1067 AST_LIST_LOCK(&helpers);
1068 AST_LIST_REMOVE(&helpers, e, list);
1069 AST_LIST_UNLOCK(&helpers);
1074 int ast_cli_register(struct ast_cli_entry *e)
1076 struct ast_cli_entry *cur;
1080 ast_join(fulle, sizeof(fulle), e->cmda);
1081 AST_LIST_LOCK(&helpers);
1083 if (find_cli(e->cmda, 1)) {
1084 AST_LIST_UNLOCK(&helpers);
1085 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1088 e->_full_cmd = ast_strdup(fulle);
1092 AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1093 int len = strlen(cur->_full_cmd);
1096 if (strncasecmp(fulle, cur->_full_cmd, len) < 0) {
1097 AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list);
1101 AST_LIST_TRAVERSE_SAFE_END;
1104 AST_LIST_INSERT_TAIL(&helpers, e, list);
1105 ret = 0; /* success */
1108 AST_LIST_UNLOCK(&helpers);
1114 * register/unregister an array of entries.
1116 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1120 for (i = 0; i < len; i++)
1121 ast_cli_register(e + i);
1124 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1128 for (i = 0; i < len; i++)
1129 ast_cli_unregister(e + i);
1133 /*! \brief helper for help_workhorse and final part of
1134 * handle_help. if locked = 0 it's just help_workhorse,
1135 * otherwise assume the list is already locked and print
1136 * an error message if not found.
1138 static int help1(int fd, char *match[], int locked)
1140 char matchstr[80] = "";
1141 struct ast_cli_entry *e;
1144 struct cli_iterator i = { NULL, NULL};
1147 ast_join(matchstr, sizeof(matchstr), match);
1148 len = strlen(matchstr);
1151 AST_LIST_LOCK(&helpers);
1152 while ( (e = cli_next(&i)) ) {
1153 /* Hide commands that start with '_' */
1154 if (e->_full_cmd[0] == '_')
1156 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1158 ast_cli(fd, "%25.25s %s\n", e->_full_cmd, e->summary);
1161 AST_LIST_UNLOCK(&helpers);
1162 if (!locked && !found && matchstr[0])
1163 ast_cli(fd, "No such command '%s'.\n", matchstr);
1167 static int help_workhorse(int fd, char *match[])
1169 return help1(fd, match, 0 /* do not print errors */);
1172 static int handle_help(int fd, int argc, char *argv[])
1175 struct ast_cli_entry *e;
1178 return RESULT_SHOWUSAGE;
1180 return help_workhorse(fd, NULL);
1182 AST_LIST_LOCK(&helpers);
1183 e = find_cli(argv + 1, 1); /* try exact match first */
1185 return help1(fd, argv + 1, 1 /* locked */);
1187 ast_cli(fd, "%s", e->usage);
1189 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1190 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1192 AST_LIST_UNLOCK(&helpers);
1193 return RESULT_SUCCESS;
1196 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1204 *trailingwhitespace = 0;
1205 if (s == NULL) /* invalid, though! */
1207 /* make a copy to store the parsed string */
1208 if (!(dup = strdup(s)))
1212 /* scan the original string copying into cur when needed */
1215 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1218 if (*s == '"' && !escaped) {
1220 if (quoted && whitespace) {
1221 /* start a quoted string from previous whitespace: new argument */
1225 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1226 /* If we are not already in whitespace, and not in a quoted string or
1227 processing an escape sequence, and just entered whitespace, then
1228 finalize the previous argument and remember that we are in whitespace
1234 } else if (*s == '\\' && !escaped) {
1238 /* we leave whitespace, and are not quoted. So it's a new argument */
1246 /* Null terminate */
1248 /* XXX put a NULL in the last argument, because some functions that take
1249 * the array may want a null-terminated array.
1250 * argc still reflects the number of non-NULL entries.
1254 *trailingwhitespace = whitespace;
1258 /*! \brief Return the number of unique matches for the generator */
1259 int ast_cli_generatornummatches(const char *text, const char *word)
1261 int matches = 0, i = 0;
1262 char *buf = NULL, *oldbuf = NULL;
1264 while ((buf = ast_cli_generator(text, word, i++))) {
1265 if (!oldbuf || strcmp(buf,oldbuf))
1276 char **ast_cli_completion_matches(const char *text, const char *word)
1278 char **match_list = NULL, *retstr, *prevstr;
1279 size_t match_list_len, max_equal, which, i;
1282 /* leave entry 0 free for the longest common substring */
1284 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1285 if (matches + 1 >= match_list_len) {
1286 match_list_len <<= 1;
1287 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1290 match_list[++matches] = retstr;
1294 return match_list; /* NULL */
1296 /* Find the longest substring that is common to all results
1297 * (it is a candidate for completion), and store a copy in entry 0.
1299 prevstr = match_list[1];
1300 max_equal = strlen(prevstr);
1301 for (which = 2; which <= matches; which++) {
1302 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1307 if (!(retstr = ast_malloc(max_equal + 1)))
1310 strncpy(retstr, match_list[1], max_equal);
1311 retstr[max_equal] = '\0';
1312 match_list[0] = retstr;
1314 /* ensure that the array is NULL terminated */
1315 if (matches + 1 >= match_list_len) {
1316 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1319 match_list[matches + 1] = NULL;
1324 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1326 char *argv[AST_MAX_ARGS];
1327 struct ast_cli_entry *e;
1328 struct cli_iterator i = { NULL, NULL };
1329 int x = 0, argindex, matchlen;
1332 char matchstr[80] = "";
1334 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1336 if (!dup) /* error */
1338 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1339 /* rebuild the command, ignore tws */
1340 ast_join(matchstr, sizeof(matchstr)-1, argv);
1342 strcat(matchstr, " "); /* XXX */
1343 matchlen = strlen(matchstr);
1345 AST_LIST_LOCK(&helpers);
1346 while( !ret && (e = cli_next(&i)) ) {
1347 int lc = strlen(e->_full_cmd);
1348 if (e->_full_cmd[0] != '_' && lc > 0 && matchlen <= lc &&
1349 !strncasecmp(matchstr, e->_full_cmd, matchlen)) {
1350 /* Found initial part, return a copy of the next word... */
1351 if (e->cmda[argindex] && ++matchnum > state)
1352 ret = strdup(e->cmda[argindex]); /* we need a malloced string */
1353 } else if (e->generator && !strncasecmp(matchstr, e->_full_cmd, lc) && matchstr[lc] < 33) {
1354 /* We have a command in its entirity within us -- theoretically only one
1355 command can have this occur */
1356 ret = e->generator(matchstr, word, argindex, state);
1360 AST_LIST_UNLOCK(&helpers);
1365 char *ast_cli_generator(const char *text, const char *word, int state)
1367 return __ast_cli_generator(text, word, state, 1);
1370 int ast_cli_command(int fd, const char *s)
1372 char *argv[AST_MAX_ARGS];
1373 struct ast_cli_entry *e;
1378 if (!(dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws))) {
1379 ast_log(LOG_ERROR, "Memory allocation failure\n");
1383 /* We need at least one entry, or ignore */
1385 AST_LIST_LOCK(&helpers);
1386 e = find_cli(argv, 0);
1389 AST_LIST_UNLOCK(&helpers);
1391 switch(e->handler(fd, x, argv)) {
1392 case RESULT_SHOWUSAGE:
1394 ast_cli(fd, "%s", e->usage);
1396 ast_cli(fd, "Invalid usage, but no usage information available.\n");
1400 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1402 AST_LIST_LOCK(&helpers);
1403 e->inuse--; /* XXX here an atomic dec would suffice */
1404 AST_LIST_UNLOCK(&helpers);