2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Standard Command Line Interface
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__
, "$Revision$")
30 #include "asterisk/_private.h"
31 #include "asterisk/paths.h" /* use ast_config_AST_MODULE_DIR */
32 #include <sys/signal.h>
37 #include "asterisk/cli.h"
38 #include "asterisk/linkedlists.h"
39 #include "asterisk/module.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/app.h"
44 #include "asterisk/lock.h"
45 #include "editline/readline/readline.h"
46 #include "asterisk/threadstorage.h"
49 * \brief map a debug or verbose value to a filename
51 struct ast_debug_file
{
53 AST_RWLIST_ENTRY(ast_debug_file
) entry
;
57 AST_RWLIST_HEAD(debug_file_list
, ast_debug_file
);
59 /*! list of filenames and their debug settings */
60 static struct debug_file_list debug_files
;
61 /*! list of filenames and their verbose settings */
62 static struct debug_file_list verbose_files
;
64 AST_THREADSTORAGE(ast_cli_buf
);
66 /*! \brief Initial buffer size for resulting strings in ast_cli() */
67 #define AST_CLI_INITLEN 256
69 void ast_cli(int fd
, const char *fmt
, ...)
75 if (!(buf
= ast_str_thread_get(&ast_cli_buf
, AST_CLI_INITLEN
)))
79 res
= ast_str_set_va(&buf
, 0, fmt
, ap
);
82 if (res
!= AST_DYNSTR_BUILD_FAILED
)
83 ast_carefulwrite(fd
, buf
->str
, strlen(buf
->str
), 100);
86 unsigned int ast_debug_get_by_file(const char *file
)
88 struct ast_debug_file
*adf
;
91 AST_RWLIST_RDLOCK(&debug_files
);
92 AST_LIST_TRAVERSE(&debug_files
, adf
, entry
) {
93 if (!strncasecmp(adf
->filename
, file
, strlen(adf
->filename
))) {
98 AST_RWLIST_UNLOCK(&debug_files
);
103 unsigned int ast_verbose_get_by_file(const char *file
)
105 struct ast_debug_file
*adf
;
106 unsigned int res
= 0;
108 AST_RWLIST_RDLOCK(&verbose_files
);
109 AST_LIST_TRAVERSE(&verbose_files
, adf
, entry
) {
110 if (!strncasecmp(adf
->filename
, file
, strlen(file
))) {
115 AST_RWLIST_UNLOCK(&verbose_files
);
120 static AST_RWLIST_HEAD_STATIC(helpers
, ast_cli_entry
);
122 static char *complete_fn(const char *word
, int state
)
128 ast_copy_string(filename
, word
, sizeof(filename
));
130 snprintf(filename
, sizeof(filename
), "%s/%s", ast_config_AST_MODULE_DIR
, word
);
132 c
= d
= filename_completion_function(filename
, state
);
134 if (c
&& word
[0] != '/')
135 c
+= (strlen(ast_config_AST_MODULE_DIR
) + 1);
144 static char *handle_load(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
146 /* "module load <mod>" */
149 e
->command
= "module load";
151 "Usage: module load <module name>\n"
152 " Loads the specified module into Asterisk.\n";
156 if (a
->pos
!= e
->args
)
158 return complete_fn(a
->word
, a
->n
);
160 if (a
->argc
!= e
->args
+ 1)
161 return CLI_SHOWUSAGE
;
162 if (ast_load_resource(a
->argv
[e
->args
])) {
163 ast_cli(a
->fd
, "Unable to load module %s\n", a
->argv
[e
->args
]);
169 static char *handle_load_deprecated(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
171 char *res
= handle_load(e
, cmd
, a
);
177 static char *handle_reload(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
183 e
->command
= "module reload";
185 "Usage: module reload [module ...]\n"
186 " Reloads configuration files for all listed modules which support\n"
187 " reloading, or for all supported modules if none are listed.\n";
191 return ast_module_helper(a
->line
, a
->word
, a
->pos
, a
->n
, a
->pos
, 1);
193 if (a
->argc
== e
->args
) {
194 ast_module_reload(NULL
);
197 for (x
= e
->args
; x
< a
->argc
; x
++) {
198 int res
= ast_module_reload(a
->argv
[x
]);
199 /* XXX reload has multiple error returns, including -1 on error and 2 on success */
202 ast_cli(a
->fd
, "No such module '%s'\n", a
->argv
[x
]);
205 ast_cli(a
->fd
, "Module '%s' does not support reload\n", a
->argv
[x
]);
212 static char *handle_reload_deprecated(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
214 char *s
= handle_reload(e
, cmd
, a
);
215 if (cmd
== CLI_INIT
) /* override command name */
216 e
->command
= "reload";
221 * \brief Find the debug or verbose file setting
222 * \arg debug 1 for debug, 0 for verbose
224 static struct ast_debug_file
*find_debug_file(const char *fn
, unsigned int debug
)
226 struct ast_debug_file
*df
= NULL
;
227 struct debug_file_list
*dfl
= debug
? &debug_files
: &verbose_files
;
229 AST_LIST_TRAVERSE(dfl
, df
, entry
) {
230 if (!strcasecmp(df
->filename
, fn
))
237 static char *handle_verbose(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
244 char **argv
= a
->argv
;
247 struct debug_file_list
*dfl
;
248 struct ast_debug_file
*adf
;
253 e
->command
= "core set {debug|verbose} [off|atleast]";
255 "Usage: core set {debug|verbose} [atleast] <level> [filename]\n"
256 " core set {debug|verbose} off\n"
257 " Sets level of debug or verbose messages to be displayed or \n"
258 " sets a filename to display debug messages from.\n"
259 " 0 or off means no messages should be displayed.\n"
260 " Equivalent to -d[d[...]] or -v[v[v...]] on startup\n";
266 /* all the above return, so we proceed with the handler.
267 * we are guaranteed to be called with argc >= e->args;
271 return CLI_SHOWUSAGE
;
272 if (!strcasecmp(argv
[e
->args
- 2], "debug")) {
274 oldval
= option_debug
;
277 dst
= &option_verbose
;
278 oldval
= option_verbose
;
281 if (argc
== e
->args
&& !strcasecmp(argv
[e
->args
- 1], "off")) {
282 unsigned int debug
= (*what
== 'C');
285 dfl
= debug
? &debug_files
: &verbose_files
;
287 AST_RWLIST_WRLOCK(dfl
);
288 while ((adf
= AST_RWLIST_REMOVE_HEAD(dfl
, entry
)))
290 ast_clear_flag(&ast_options
, debug
? AST_OPT_FLAG_DEBUG_FILE
: AST_OPT_FLAG_VERBOSE_FILE
);
291 AST_RWLIST_UNLOCK(dfl
);
295 if (!strcasecmp(argv
[e
->args
-1], "atleast"))
297 if (argc
!= e
->args
+ atleast
&& argc
!= e
->args
+ atleast
+ 1)
298 return CLI_SHOWUSAGE
;
299 if (sscanf(argv
[e
->args
+ atleast
- 1], "%d", &newlevel
) != 1)
300 return CLI_SHOWUSAGE
;
301 if (argc
== e
->args
+ atleast
+ 1) {
302 unsigned int debug
= (*what
== 'C');
303 dfl
= debug
? &debug_files
: &verbose_files
;
305 fn
= argv
[e
->args
+ atleast
];
307 AST_RWLIST_WRLOCK(dfl
);
309 if ((adf
= find_debug_file(fn
, debug
)) && !newlevel
) {
310 AST_RWLIST_REMOVE(dfl
, adf
, entry
);
311 if (AST_RWLIST_EMPTY(dfl
))
312 ast_clear_flag(&ast_options
, debug
? AST_OPT_FLAG_DEBUG_FILE
: AST_OPT_FLAG_VERBOSE_FILE
);
313 AST_RWLIST_UNLOCK(dfl
);
314 ast_cli(fd
, "%s was %d and has been set to 0 for '%s'\n", what
, adf
->level
, fn
);
320 if ((atleast
&& newlevel
< adf
->level
) || adf
->level
== newlevel
) {
321 ast_cli(fd
, "%s is %d for '%s'\n", what
, adf
->level
, fn
);
322 AST_RWLIST_UNLOCK(dfl
);
325 } else if (!(adf
= ast_calloc(1, sizeof(*adf
) + strlen(fn
) + 1))) {
326 AST_RWLIST_UNLOCK(dfl
);
331 adf
->level
= newlevel
;
332 strcpy(adf
->filename
, fn
);
334 ast_set_flag(&ast_options
, debug
? AST_OPT_FLAG_DEBUG_FILE
: AST_OPT_FLAG_VERBOSE_FILE
);
336 AST_RWLIST_INSERT_TAIL(dfl
, adf
, entry
);
337 AST_RWLIST_UNLOCK(dfl
);
339 ast_cli(fd
, "%s was %d and has been set to %d for '%s'\n", what
, oldval
, adf
->level
, adf
->filename
);
345 if (!atleast
|| newlevel
> *dst
)
347 if (oldval
> 0 && *dst
== 0)
348 ast_cli(fd
, "%s is now OFF\n", what
);
351 ast_cli(fd
, "%s is at least %d\n", what
, *dst
);
353 ast_cli(fd
, "%s was %d and is now %d\n", what
, oldval
, *dst
);
359 static char *handle_logger_mute(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
363 e
->command
= "logger mute";
365 "Usage: logger mute\n"
366 " Disables logging output to the current console, making it possible to\n"
367 " gather information without being disturbed by scrolling lines.\n";
373 if (a
->argc
< 2 || a
->argc
> 3)
374 return CLI_SHOWUSAGE
;
376 if (a
->argc
== 3 && !strcasecmp(a
->argv
[2], "silent"))
377 ast_console_toggle_mute(a
->fd
, 1);
379 ast_console_toggle_mute(a
->fd
, 0);
384 static char *handle_unload(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
386 /* "module unload mod_1 [mod_2 .. mod_N]" */
388 int force
= AST_FORCE_SOFT
;
393 e
->command
= "module unload";
395 "Usage: module unload [-f|-h] <module_1> [<module_2> ... ]\n"
396 " Unloads the specified module from Asterisk. The -f\n"
397 " option causes the module to be unloaded even if it is\n"
398 " in use (may cause a crash) and the -h module causes the\n"
399 " module to be unloaded even if the module says it cannot, \n"
400 " which almost always will cause a crash.\n";
404 return ast_module_helper(a
->line
, a
->word
, a
->pos
, a
->n
, a
->pos
, 0);
406 if (a
->argc
< e
->args
+ 1)
407 return CLI_SHOWUSAGE
;
408 x
= e
->args
; /* first argument */
412 force
= AST_FORCE_FIRM
;
413 else if (s
[1] == 'h')
414 force
= AST_FORCE_HARD
;
416 return CLI_SHOWUSAGE
;
417 if (a
->argc
< e
->args
+ 2) /* need at least one module name */
418 return CLI_SHOWUSAGE
;
419 x
++; /* skip this argument */
422 for (; x
< a
->argc
; x
++) {
423 if (ast_unload_resource(a
->argv
[x
], force
)) {
424 ast_cli(a
->fd
, "Unable to unload resource %s\n", a
->argv
[x
]);
431 static char *handle_unload_deprecated(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
433 char *res
= handle_unload(e
, cmd
, a
);
435 e
->command
= "unload"; /* XXX override */
439 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
440 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
442 AST_MUTEX_DEFINE_STATIC(climodentrylock
);
443 static int climodentryfd
= -1;
445 static int modlist_modentry(const char *module
, const char *description
, int usecnt
, const char *like
)
447 /* Comparing the like with the module */
448 if (strcasestr(module
, like
) ) {
449 ast_cli(climodentryfd
, MODLIST_FORMAT
, module
, description
, usecnt
);
455 static void print_uptimestr(int fd
, struct timeval timeval
, const char *prefix
, int printsec
)
457 int x
; /* the main part - years, weeks, etc. */
461 #define MINUTE (SECOND*60)
462 #define HOUR (MINUTE*60)
463 #define DAY (HOUR*24)
465 #define YEAR (DAY*365)
466 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
467 if (timeval
.tv_sec
< 0) /* invalid, nothing to show */
470 if (printsec
) { /* plain seconds output */
471 ast_cli(fd
, "%s: %lu\n", prefix
, (u_long
)timeval
.tv_sec
);
474 out
= ast_str_alloca(256);
475 if (timeval
.tv_sec
> YEAR
) {
476 x
= (timeval
.tv_sec
/ YEAR
);
477 timeval
.tv_sec
-= (x
* YEAR
);
478 ast_str_append(&out
, 0, "%d year%s%s ", x
, ESS(x
),NEEDCOMMA(timeval
.tv_sec
));
480 if (timeval
.tv_sec
> WEEK
) {
481 x
= (timeval
.tv_sec
/ WEEK
);
482 timeval
.tv_sec
-= (x
* WEEK
);
483 ast_str_append(&out
, 0, "%d week%s%s ", x
, ESS(x
),NEEDCOMMA(timeval
.tv_sec
));
485 if (timeval
.tv_sec
> DAY
) {
486 x
= (timeval
.tv_sec
/ DAY
);
487 timeval
.tv_sec
-= (x
* DAY
);
488 ast_str_append(&out
, 0, "%d day%s%s ", x
, ESS(x
),NEEDCOMMA(timeval
.tv_sec
));
490 if (timeval
.tv_sec
> HOUR
) {
491 x
= (timeval
.tv_sec
/ HOUR
);
492 timeval
.tv_sec
-= (x
* HOUR
);
493 ast_str_append(&out
, 0, "%d hour%s%s ", x
, ESS(x
),NEEDCOMMA(timeval
.tv_sec
));
495 if (timeval
.tv_sec
> MINUTE
) {
496 x
= (timeval
.tv_sec
/ MINUTE
);
497 timeval
.tv_sec
-= (x
* MINUTE
);
498 ast_str_append(&out
, 0, "%d minute%s%s ", x
, ESS(x
),NEEDCOMMA(timeval
.tv_sec
));
501 if (x
> 0 || out
->used
== 0) /* if there is nothing, print 0 seconds */
502 ast_str_append(&out
, 0, "%d second%s ", x
, ESS(x
));
503 ast_cli(fd
, "%s: %s\n", prefix
, out
->str
);
506 static char * handle_showuptime(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
508 struct timeval curtime
= ast_tvnow();
513 e
->command
= "core show uptime [seconds]";
515 "Usage: core show uptime [seconds]\n"
516 " Shows Asterisk uptime information.\n"
517 " The seconds word returns the uptime in seconds only.\n";
523 /* regular handler */
524 if (a
->argc
== e
->args
&& !strcasecmp(a
->argv
[e
->args
-1],"seconds"))
526 else if (a
->argc
== e
->args
-1)
529 return CLI_SHOWUSAGE
;
530 if (ast_startuptime
.tv_sec
)
531 print_uptimestr(a
->fd
, ast_tvsub(curtime
, ast_startuptime
), "System uptime", printsec
);
532 if (ast_lastreloadtime
.tv_sec
)
533 print_uptimestr(a
->fd
, ast_tvsub(curtime
, ast_lastreloadtime
), "Last reload", printsec
);
537 static char *handle_modlist(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
543 e
->command
= "module show [like]";
545 "Usage: module show [like keyword]\n"
546 " Shows Asterisk modules currently in use, and usage statistics.\n";
550 if (a
->pos
== e
->args
)
551 return ast_module_helper(a
->line
, a
->word
, a
->pos
, a
->n
, a
->pos
, 0);
555 /* all the above return, so we proceed with the handler.
556 * we are guaranteed to have argc >= e->args
558 if (a
->argc
== e
->args
- 1)
560 else if (a
->argc
== e
->args
+ 1 && !strcasecmp(a
->argv
[e
->args
-1], "like") )
561 like
= a
->argv
[e
->args
];
563 return CLI_SHOWUSAGE
;
565 ast_mutex_lock(&climodentrylock
);
566 climodentryfd
= a
->fd
; /* global, protected by climodentrylock */
567 ast_cli(a
->fd
, MODLIST_FORMAT2
, "Module", "Description", "Use Count");
568 ast_cli(a
->fd
,"%d modules loaded\n", ast_update_module_list(modlist_modentry
, like
));
570 ast_mutex_unlock(&climodentrylock
);
573 #undef MODLIST_FORMAT
574 #undef MODLIST_FORMAT2
576 static char *handle_showcalls(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
578 struct timeval curtime
= ast_tvnow();
579 int showuptime
, printsec
;
583 e
->command
= "core show calls [uptime]";
585 "Usage: core show calls [uptime] [seconds]\n"
586 " Lists number of currently active calls and total number of calls\n"
587 " processed through PBX since last restart. If 'uptime' is specified\n"
588 " the system uptime is also displayed. If 'seconds' is specified in\n"
589 " addition to 'uptime', the system uptime is displayed in seconds.\n";
593 if (a
->pos
!= e
->args
)
595 return a
->n
== 0 ? ast_strdup("seconds") : NULL
;
598 /* regular handler */
599 if (a
->argc
>= e
->args
&& !strcasecmp(a
->argv
[e
->args
-1],"uptime")) {
602 if (a
->argc
== e
->args
+1 && !strcasecmp(a
->argv
[e
->args
],"seconds"))
604 else if (a
->argc
== e
->args
)
607 return CLI_SHOWUSAGE
;
608 } else if (a
->argc
== e
->args
-1) {
612 return CLI_SHOWUSAGE
;
614 if (option_maxcalls
) {
615 ast_cli(a
->fd
, "%d of %d max active call%s (%5.2f%% of capacity)\n",
616 ast_active_calls(), option_maxcalls
, ESS(ast_active_calls()),
617 ((double)ast_active_calls() / (double)option_maxcalls
) * 100.0);
619 ast_cli(a
->fd
, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
622 ast_cli(a
->fd
, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
624 if (ast_startuptime
.tv_sec
&& showuptime
) {
625 print_uptimestr(a
->fd
, ast_tvsub(curtime
, ast_startuptime
), "System uptime", printsec
);
628 return RESULT_SUCCESS
;
631 static char *handle_chanlist(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
633 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
634 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
635 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s!%s\n"
636 #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"
637 #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"
639 struct ast_channel
*c
= NULL
;
640 int numchans
= 0, concise
= 0, verbose
= 0, count
= 0;
646 e
->command
= "core show channels [concise|verbose|count]";
648 "Usage: core show channels [concise|verbose|count]\n"
649 " Lists currently defined channels and some information about them. If\n"
650 " 'concise' is specified, the format is abridged and in a more easily\n"
651 " machine parsable format. If 'verbose' is specified, the output includes\n"
652 " more and longer fields. If 'count' is specified only the channel and call\n"
653 " count is output.\n"
654 " The 'concise' option is deprecated and will be removed from future versions\n"
665 if (a
->argc
== e
->args
) {
666 if (!strcasecmp(argv
[e
->args
-1],"concise"))
668 else if (!strcasecmp(argv
[e
->args
-1],"verbose"))
670 else if (!strcasecmp(argv
[e
->args
-1],"count"))
673 return CLI_SHOWUSAGE
;
674 } else if (a
->argc
!= e
->args
- 1)
675 return CLI_SHOWUSAGE
;
678 if (!concise
&& !verbose
)
679 ast_cli(fd
, FORMAT_STRING2
, "Channel", "Location", "State", "Application(Data)");
681 ast_cli(fd
, VERBOSE_FORMAT_STRING2
, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
682 "CallerID", "Duration", "Accountcode", "BridgedTo");
685 while ((c
= ast_channel_walk_locked(c
)) != NULL
) {
686 struct ast_channel
*bc
= ast_bridged_channel(c
);
687 char durbuf
[10] = "-";
690 if ((concise
|| verbose
) && c
->cdr
&& !ast_tvzero(c
->cdr
->start
)) {
691 int duration
= (int)(ast_tvdiff_ms(ast_tvnow(), c
->cdr
->start
) / 1000);
693 int durh
= duration
/ 3600;
694 int durm
= (duration
% 3600) / 60;
695 int durs
= duration
% 60;
696 snprintf(durbuf
, sizeof(durbuf
), "%02d:%02d:%02d", durh
, durm
, durs
);
698 snprintf(durbuf
, sizeof(durbuf
), "%d", duration
);
702 ast_cli(fd
, CONCISE_FORMAT_STRING
, c
->name
, c
->context
, c
->exten
, c
->priority
, ast_state2str(c
->_state
),
703 c
->appl
? c
->appl
: "(None)",
704 S_OR(c
->data
, ""), /* XXX different from verbose ? */
705 S_OR(c
->cid
.cid_num
, ""),
706 S_OR(c
->accountcode
, ""),
709 bc
? bc
->name
: "(None)",
711 } else if (verbose
) {
712 ast_cli(fd
, VERBOSE_FORMAT_STRING
, c
->name
, c
->context
, c
->exten
, c
->priority
, ast_state2str(c
->_state
),
713 c
->appl
? c
->appl
: "(None)",
714 c
->data
? S_OR(c
->data
, "(Empty)" ): "(None)",
715 S_OR(c
->cid
.cid_num
, ""),
717 S_OR(c
->accountcode
, ""),
718 bc
? bc
->name
: "(None)");
720 char locbuf
[40] = "(None)";
721 char appdata
[40] = "(None)";
723 if (!ast_strlen_zero(c
->context
) && !ast_strlen_zero(c
->exten
))
724 snprintf(locbuf
, sizeof(locbuf
), "%s@%s:%d", c
->exten
, c
->context
, c
->priority
);
726 snprintf(appdata
, sizeof(appdata
), "%s(%s)", c
->appl
, S_OR(c
->data
, ""));
727 ast_cli(fd
, FORMAT_STRING
, c
->name
, locbuf
, ast_state2str(c
->_state
), appdata
);
731 ast_channel_unlock(c
);
734 ast_cli(fd
, "%d active channel%s\n", numchans
, ESS(numchans
));
736 ast_cli(fd
, "%d of %d max active call%s (%5.2f%% of capacity)\n",
737 ast_active_calls(), option_maxcalls
, ESS(ast_active_calls()),
738 ((double)ast_active_calls() / (double)option_maxcalls
) * 100.0);
740 ast_cli(fd
, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
742 ast_cli(fd
, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
747 #undef FORMAT_STRING2
748 #undef CONCISE_FORMAT_STRING
749 #undef VERBOSE_FORMAT_STRING
750 #undef VERBOSE_FORMAT_STRING2
753 static char *handle_softhangup(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
755 struct ast_channel
*c
=NULL
;
759 e
->command
= "soft hangup";
761 "Usage: soft hangup <channel>\n"
762 " Request that a channel be hung up. The hangup takes effect\n"
763 " the next time the driver reads or writes from the channel\n";
766 return ast_complete_channels(a
->line
, a
->word
, a
->pos
, a
->n
, 2);
769 return CLI_SHOWUSAGE
;
770 c
= ast_get_channel_by_name_locked(a
->argv
[2]);
772 ast_cli(a
->fd
, "Requested Hangup on channel '%s'\n", c
->name
);
773 ast_softhangup(c
, AST_SOFTHANGUP_EXPLICIT
);
774 ast_channel_unlock(c
);
776 ast_cli(a
->fd
, "%s is not a known channel\n", a
->argv
[2]);
780 static char *__ast_cli_generator(const char *text
, const char *word
, int state
, int lock
);
782 static char *handle_commandmatchesarray(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
792 e
->command
= "_command matchesarray";
794 "Usage: _command matchesarray \"<line>\" text \n"
795 " This function is used internally to help with command completion and should.\n"
796 " never be called by the user directly.\n";
803 return CLI_SHOWUSAGE
;
804 if (!(buf
= ast_malloc(buflen
)))
807 matches
= ast_cli_completion_matches(a
->argv
[2], a
->argv
[3]);
809 for (x
=0; matches
[x
]; x
++) {
810 matchlen
= strlen(matches
[x
]) + 1;
811 if (len
+ matchlen
>= buflen
) {
812 buflen
+= matchlen
* 3;
814 if (!(buf
= ast_realloc(obuf
, buflen
)))
815 /* Memory allocation failure... Just free old buffer and be done */
819 len
+= sprintf( buf
+ len
, "%s ", matches
[x
]);
820 ast_free(matches
[x
]);
827 ast_cli(a
->fd
, "%s%s",buf
, AST_CLI_COMPLETE_EOF
);
830 ast_cli(a
->fd
, "NULL\n");
837 static char *handle_commandnummatches(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
843 e
->command
= "_command nummatches";
845 "Usage: _command nummatches \"<line>\" text \n"
846 " This function is used internally to help with command completion and should.\n"
847 " never be called by the user directly.\n";
854 return CLI_SHOWUSAGE
;
856 matches
= ast_cli_generatornummatches(a
->argv
[2], a
->argv
[3]);
858 ast_cli(a
->fd
, "%d", matches
);
863 static char *handle_commandcomplete(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
868 e
->command
= "_command complete";
870 "Usage: _command complete \"<line>\" text state\n"
871 " This function is used internally to help with command completion and should.\n"
872 " never be called by the user directly.\n";
878 return CLI_SHOWUSAGE
;
879 buf
= __ast_cli_generator(a
->argv
[2], a
->argv
[3], atoi(a
->argv
[4]), 0);
881 ast_cli(a
->fd
, "%s", buf
);
884 ast_cli(a
->fd
, "NULL\n");
888 static char *handle_core_set_debug_channel(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
890 struct ast_channel
*c
= NULL
;
891 int is_all
, is_off
= 0;
895 e
->command
= "core set debug channel";
897 "Usage: core set debug channel <all|channel> [off]\n"
898 " Enables/disables debugging on all or on a specific channel.\n";
902 /* XXX remember to handle the optional "off" */
903 if (a
->pos
!= e
->args
)
905 return a
->n
== 0 ? ast_strdup("all") : ast_complete_channels(a
->line
, a
->word
, a
->pos
, a
->n
- 1, e
->args
);
907 /* 'core set debug channel {all|chan_id}' */
908 if (a
->argc
== e
->args
+ 2) {
909 if (!strcasecmp(a
->argv
[e
->args
+ 1], "off"))
912 return CLI_SHOWUSAGE
;
913 } else if (a
->argc
!= e
->args
+ 1)
914 return CLI_SHOWUSAGE
;
916 is_all
= !strcasecmp("all", a
->argv
[e
->args
]);
919 global_fin
&= ~DEBUGCHAN_FLAG
;
920 global_fout
&= ~DEBUGCHAN_FLAG
;
922 global_fin
|= DEBUGCHAN_FLAG
;
923 global_fout
|= DEBUGCHAN_FLAG
;
925 c
= ast_channel_walk_locked(NULL
);
927 c
= ast_get_channel_by_name_locked(a
->argv
[e
->args
]);
929 ast_cli(a
->fd
, "No such channel %s\n", a
->argv
[e
->args
]);
932 if (!(c
->fin
& DEBUGCHAN_FLAG
) || !(c
->fout
& DEBUGCHAN_FLAG
)) {
934 c
->fin
&= ~DEBUGCHAN_FLAG
;
935 c
->fout
&= ~DEBUGCHAN_FLAG
;
937 c
->fin
|= DEBUGCHAN_FLAG
;
938 c
->fout
|= DEBUGCHAN_FLAG
;
940 ast_cli(a
->fd
, "Debugging %s on channel %s\n", is_off
? "disabled" : "enabled", c
->name
);
942 ast_channel_unlock(c
);
945 c
= ast_channel_walk_locked(c
);
947 ast_cli(a
->fd
, "Debugging on new channels is %s\n", is_off
? "disabled" : "enabled");
951 static char *handle_debugchan_deprecated(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
955 if (cmd
== CLI_HANDLER
&& a
->argc
!= e
->args
+ 1)
956 return CLI_SHOWUSAGE
;
957 res
= handle_core_set_debug_channel(e
, cmd
, a
);
959 e
->command
= "debug channel";
963 static char *handle_nodebugchan_deprecated(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
966 if (cmd
== CLI_HANDLER
) {
967 if (a
->argc
!= e
->args
+ 1)
968 return CLI_SHOWUSAGE
;
969 /* pretend we have an extra "off" at the end. We can do this as the array
970 * is NULL terminated so we overwrite that entry.
972 a
->argv
[e
->args
+1] = "off";
975 res
= handle_core_set_debug_channel(e
, cmd
, a
);
977 e
->command
= "no debug channel";
981 static char *handle_showchan(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
983 struct ast_channel
*c
=NULL
;
985 struct ast_str
*out
= ast_str_alloca(2048);
987 char nf
[256], wf
[256], rf
[256];
988 long elapsed_seconds
=0;
989 int hour
=0, min
=0, sec
=0;
996 e
->command
= "core show channel";
998 "Usage: core show channel <channel>\n"
999 " Shows lots of information about the specified channel.\n";
1002 return ast_complete_channels(a
->line
, a
->word
, a
->pos
, a
->n
, 3);
1006 return CLI_SHOWUSAGE
;
1008 c
= ast_get_channel_by_name_locked(a
->argv
[3]);
1010 ast_cli(a
->fd
, "%s is not a known channel\n", a
->argv
[3]);
1014 elapsed_seconds
= now
.tv_sec
- c
->cdr
->start
.tv_sec
;
1015 hour
= elapsed_seconds
/ 3600;
1016 min
= (elapsed_seconds
% 3600) / 60;
1017 sec
= elapsed_seconds
% 60;
1018 snprintf(cdrtime
, sizeof(cdrtime
), "%dh%dm%ds", hour
, min
, sec
);
1020 strcpy(cdrtime
, "N/A");
1027 " Caller ID Name: %s\n"
1028 " DNID Digits: %s\n"
1032 " NativeFormats: %s\n"
1033 " WriteFormat: %s\n"
1035 " WriteTranscode: %s\n"
1036 " ReadTranscode: %s\n"
1037 "1st File Descriptor: %d\n"
1038 " Frames in: %d%s\n"
1039 " Frames out: %d%s\n"
1040 " Time to Hangup: %ld\n"
1041 " Elapsed Time: %s\n"
1042 " Direct Bridge: %s\n"
1043 "Indirect Bridge: %s\n"
1048 " Call Group: %llu\n"
1049 " Pickup Group: %llu\n"
1050 " Application: %s\n"
1052 " Blocking in: %s\n",
1053 c
->name
, c
->tech
->type
, c
->uniqueid
,
1054 S_OR(c
->cid
.cid_num
, "(N/A)"),
1055 S_OR(c
->cid
.cid_name
, "(N/A)"),
1056 S_OR(c
->cid
.cid_dnid
, "(N/A)"),
1058 ast_state2str(c
->_state
), c
->_state
, c
->rings
,
1059 ast_getformatname_multiple(nf
, sizeof(nf
), c
->nativeformats
),
1060 ast_getformatname_multiple(wf
, sizeof(wf
), c
->writeformat
),
1061 ast_getformatname_multiple(rf
, sizeof(rf
), c
->readformat
),
1062 c
->writetrans
? "Yes" : "No",
1063 c
->readtrans
? "Yes" : "No",
1065 c
->fin
& ~DEBUGCHAN_FLAG
, (c
->fin
& DEBUGCHAN_FLAG
) ? " (DEBUGGED)" : "",
1066 c
->fout
& ~DEBUGCHAN_FLAG
, (c
->fout
& DEBUGCHAN_FLAG
) ? " (DEBUGGED)" : "",
1067 (long)c
->whentohangup
.tv_sec
,
1068 cdrtime
, c
->_bridge
? c
->_bridge
->name
: "<none>", ast_bridged_channel(c
) ? ast_bridged_channel(c
)->name
: "<none>",
1069 c
->context
, c
->exten
, c
->priority
, c
->callgroup
, c
->pickupgroup
, ( c
->appl
? c
->appl
: "(N/A)" ),
1070 ( c
-> data
? S_OR(c
->data
, "(Empty)") : "(None)"),
1071 (ast_test_flag(c
, AST_FLAG_BLOCKING
) ? c
->blockproc
: "(Not Blocking)"));
1073 if (pbx_builtin_serialize_variables(c
, &out
))
1074 ast_cli(a
->fd
," Variables:\n%s\n", out
->str
);
1075 if (c
->cdr
&& ast_cdr_serialize_variables(c
->cdr
, &out
, '=', '\n', 1))
1076 ast_cli(a
->fd
," CDR Variables:\n%s\n", out
->str
);
1077 #ifdef CHANNEL_TRACE
1078 trace_enabled
= ast_channel_trace_is_enabled(c
);
1079 ast_cli(a
->fd
, " Context Trace: %s\n", trace_enabled
? "Enabled" : "Disabled");
1080 if (trace_enabled
&& ast_channel_trace_serialize(c
, &out
))
1081 ast_cli(a
->fd
, " Trace:\n%s\n", out
->str
);
1083 ast_channel_unlock(c
);
1088 * helper function to generate CLI matches from a fixed set of values.
1089 * A NULL word is acceptable.
1091 char *ast_cli_complete(const char *word
, char *const choices
[], int state
)
1093 int i
, which
= 0, len
;
1094 len
= ast_strlen_zero(word
) ? 0 : strlen(word
);
1096 for (i
= 0; choices
[i
]; i
++) {
1097 if ((!len
|| !strncasecmp(word
, choices
[i
], len
)) && ++which
> state
)
1098 return ast_strdup(choices
[i
]);
1103 char *ast_complete_channels(const char *line
, const char *word
, int pos
, int state
, int rpos
)
1105 struct ast_channel
*c
= NULL
;
1108 char notfound
= '\0';
1109 char *ret
= ¬found
; /* so NULL can break the loop */
1114 wordlen
= strlen(word
);
1116 while (ret
== ¬found
&& (c
= ast_channel_walk_locked(c
))) {
1117 if (!strncasecmp(word
, c
->name
, wordlen
) && ++which
> state
)
1118 ret
= ast_strdup(c
->name
);
1119 ast_channel_unlock(c
);
1121 return ret
== ¬found
? NULL
: ret
;
1124 static char *group_show_channels(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
1126 #define FORMAT_STRING "%-25s %-20s %-20s\n"
1128 struct ast_group_info
*gi
= NULL
;
1131 int havepattern
= 0;
1135 e
->command
= "group show channels";
1137 "Usage: group show channels [pattern]\n"
1138 " Lists all currently active channels with channel group(s) specified.\n"
1139 " Optional regular expression pattern is matched to group names for each\n"
1146 if (a
->argc
< 3 || a
->argc
> 4)
1147 return CLI_SHOWUSAGE
;
1150 if (regcomp(®exbuf
, a
->argv
[3], REG_EXTENDED
| REG_NOSUB
))
1151 return CLI_SHOWUSAGE
;
1155 ast_cli(a
->fd
, FORMAT_STRING
, "Channel", "Group", "Category");
1157 ast_app_group_list_rdlock();
1159 gi
= ast_app_group_list_head();
1161 if (!havepattern
|| !regexec(®exbuf
, gi
->group
, 0, NULL
, 0)) {
1162 ast_cli(a
->fd
, FORMAT_STRING
, gi
->chan
->name
, gi
->group
, (ast_strlen_zero(gi
->category
) ? "(default)" : gi
->category
));
1165 gi
= AST_LIST_NEXT(gi
, list
);
1168 ast_app_group_list_unlock();
1173 ast_cli(a
->fd
, "%d active channel%s\n", numchans
, ESS(numchans
));
1175 #undef FORMAT_STRING
1178 static struct ast_cli_entry cli_debug_channel_deprecated
= AST_CLI_DEFINE(handle_debugchan_deprecated
, "Enable debugging on channel");
1179 static struct ast_cli_entry cli_module_load_deprecated
= AST_CLI_DEFINE(handle_load_deprecated
, "Load a module");
1180 static struct ast_cli_entry cli_module_reload_deprecated
= AST_CLI_DEFINE(handle_reload_deprecated
, "reload modules by name");
1181 static struct ast_cli_entry cli_module_unload_deprecated
= AST_CLI_DEFINE(handle_unload_deprecated
, "unload modules by name");
1183 static char *handle_help(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
);
1185 static struct ast_cli_entry cli_cli
[] = {
1186 /* Deprecated, but preferred command is now consolidated (and already has a deprecated command for it). */
1187 AST_CLI_DEFINE(handle_commandcomplete
, "Command complete"),
1188 AST_CLI_DEFINE(handle_commandnummatches
, "Returns number of command matches"),
1189 AST_CLI_DEFINE(handle_commandmatchesarray
, "Returns command matches array"),
1191 AST_CLI_DEFINE(handle_nodebugchan_deprecated
, "Disable debugging on channel(s)"),
1193 AST_CLI_DEFINE(handle_chanlist
, "Display information on channels"),
1195 AST_CLI_DEFINE(handle_showcalls
, "Display information on calls"),
1197 AST_CLI_DEFINE(handle_showchan
, "Display information on a specific channel"),
1199 AST_CLI_DEFINE(handle_core_set_debug_channel
, "Enable/disable debugging on a channel",
1200 .deprecate_cmd
= &cli_debug_channel_deprecated
),
1202 AST_CLI_DEFINE(handle_verbose
, "Set level of debug/verbose chattiness"),
1204 AST_CLI_DEFINE(group_show_channels
, "Display active channels with group(s)"),
1206 AST_CLI_DEFINE(handle_help
, "Display help list, or specific help on a command"),
1208 AST_CLI_DEFINE(handle_logger_mute
, "Toggle logging output to a console"),
1210 AST_CLI_DEFINE(handle_modlist
, "List modules and info"),
1212 AST_CLI_DEFINE(handle_load
, "Load a module by name", .deprecate_cmd
= &cli_module_load_deprecated
),
1214 AST_CLI_DEFINE(handle_reload
, "Reload configuration", .deprecate_cmd
= &cli_module_reload_deprecated
),
1216 AST_CLI_DEFINE(handle_unload
, "Unload a module by name", .deprecate_cmd
= &cli_module_unload_deprecated
),
1218 AST_CLI_DEFINE(handle_showuptime
, "Show uptime information"),
1220 AST_CLI_DEFINE(handle_softhangup
, "Request a hangup on a given channel"),
1224 * Some regexp characters in cli arguments are reserved and used as separators.
1226 static const char cli_rsvd
[] = "[]{}|*%";
1229 * initialize the _full_cmd string and related parameters,
1230 * return 0 on success, -1 on error.
1232 static int set_full_cmd(struct ast_cli_entry
*e
)
1237 ast_join(buf
, sizeof(buf
), e
->cmda
);
1238 e
->_full_cmd
= ast_strdup(buf
);
1239 if (!e
->_full_cmd
) {
1240 ast_log(LOG_WARNING
, "-- cannot allocate <%s>\n", buf
);
1243 e
->cmdlen
= strcspn(e
->_full_cmd
, cli_rsvd
);
1244 for (i
= 0; e
->cmda
[i
]; i
++)
1250 /*! \brief initialize the _full_cmd string in * each of the builtins. */
1251 void ast_builtins_init(void)
1253 ast_cli_register_multiple(cli_cli
, sizeof(cli_cli
) / sizeof(struct ast_cli_entry
));
1256 static struct ast_cli_entry
*cli_next(struct ast_cli_entry
*e
)
1259 e
= AST_LIST_FIRST(&helpers
);
1261 e
= AST_LIST_NEXT(e
, list
);
1266 * match a word in the CLI entry.
1267 * returns -1 on mismatch, 0 on match of an optional word,
1268 * 1 on match of a full word.
1270 * The pattern can be
1271 * any_word match for equal
1272 * [foo|bar|baz] optionally, one of these words
1273 * {foo|bar|baz} exactly, one of these words
1276 static int word_match(const char *cmd
, const char *cli_word
)
1281 if (ast_strlen_zero(cmd
) || ast_strlen_zero(cli_word
))
1283 if (!strchr(cli_rsvd
, cli_word
[0])) /* normal match */
1284 return (strcasecmp(cmd
, cli_word
) == 0) ? 1 : -1;
1285 /* regexp match, takes [foo|bar] or {foo|bar} */
1287 /* wildcard match - will extend in the future */
1288 if (l
> 0 && cli_word
[0] == '%') {
1289 return 1; /* wildcard */
1291 pos
= strcasestr(cli_word
, cmd
);
1292 if (pos
== NULL
) /* not found, say ok if optional */
1293 return cli_word
[0] == '[' ? 0 : -1;
1294 if (pos
== cli_word
) /* no valid match at the beginning */
1296 if (strchr(cli_rsvd
, pos
[-1]) && strchr(cli_rsvd
, pos
[l
]))
1297 return 1; /* valid match */
1298 return -1; /* not found */
1301 /*! \brief if word is a valid prefix for token, returns the pos-th
1302 * match as a malloced string, or NULL otherwise.
1303 * Always tell in *actual how many matches we got.
1305 static char *is_prefix(const char *word
, const char *token
,
1306 int pos
, int *actual
)
1312 if (ast_strlen_zero(token
))
1314 if (ast_strlen_zero(word
))
1315 word
= ""; /* dummy */
1317 if (strcspn(word
, cli_rsvd
) != lw
)
1318 return NULL
; /* no match if word has reserved chars */
1319 if (strchr(cli_rsvd
, token
[0]) == NULL
) { /* regular match */
1320 if (strncasecmp(token
, word
, lw
)) /* no match */
1323 return (pos
!= 0) ? NULL
: ast_strdup(token
);
1325 /* now handle regexp match */
1327 /* Wildcard always matches, so we never do is_prefix on them */
1329 t1
= ast_strdupa(token
+ 1); /* copy, skipping first char */
1330 while (pos
>= 0 && (s
= strsep(&t1
, cli_rsvd
)) && *s
) {
1331 if (*s
== '%') /* wildcard */
1333 if (strncasecmp(s
, word
, lw
)) /* no match */
1337 return ast_strdup(s
);
1343 * \brief locate a cli command in the 'helpers' list (which must be locked).
1344 * exact has 3 values:
1345 * 0 returns if the search key is equal or longer than the entry.
1346 * note that trailing optional arguments are skipped.
1347 * -1 true if the mismatch is on the last word XXX not true!
1348 * 1 true only on complete, exact match.
1350 * The search compares word by word taking care of regexps in e->cmda
1352 static struct ast_cli_entry
*find_cli(char *const cmds
[], int match_type
)
1354 int matchlen
= -1; /* length of longest match so far */
1355 struct ast_cli_entry
*cand
= NULL
, *e
=NULL
;
1357 while ( (e
= cli_next(e
)) ) {
1358 /* word-by word regexp comparison */
1359 char * const *src
= cmds
;
1360 char * const *dst
= e
->cmda
;
1362 for (;; dst
++, src
+= n
) {
1363 n
= word_match(*src
, *dst
);
1367 if (ast_strlen_zero(*dst
) || ((*dst
)[0] == '[' && ast_strlen_zero(dst
[1]))) {
1368 /* no more words in 'e' */
1369 if (ast_strlen_zero(*src
)) /* exact match, cannot do better */
1371 /* Here, cmds has more words than the entry 'e' */
1372 if (match_type
!= 0) /* but we look for almost exact match... */
1373 continue; /* so we skip this one. */
1374 /* otherwise we like it (case 0) */
1375 } else { /* still words in 'e' */
1376 if (ast_strlen_zero(*src
))
1377 continue; /* cmds is shorter than 'e', not good */
1378 /* Here we have leftover words in cmds and 'e',
1379 * but there is a mismatch. We only accept this one if match_type == -1
1380 * and this is the last word for both.
1382 if (match_type
!= -1 || !ast_strlen_zero(src
[1]) ||
1383 !ast_strlen_zero(dst
[1])) /* not the one we look for */
1385 /* good, we are in case match_type == -1 and mismatch on last word */
1387 if (src
- cmds
> matchlen
) { /* remember the candidate */
1388 matchlen
= src
- cmds
;
1392 return e
? e
: cand
;
1395 static char *find_best(char *argv
[])
1397 static char cmdline
[80];
1399 /* See how close we get, then print the candidate */
1400 char *myargv
[AST_MAX_CMD_LEN
];
1401 for (x
=0;x
<AST_MAX_CMD_LEN
;x
++)
1403 AST_RWLIST_RDLOCK(&helpers
);
1404 for (x
=0;argv
[x
];x
++) {
1405 myargv
[x
] = argv
[x
];
1406 if (!find_cli(myargv
, -1))
1409 AST_RWLIST_UNLOCK(&helpers
);
1410 ast_join(cmdline
, sizeof(cmdline
), myargv
);
1414 static int __ast_cli_unregister(struct ast_cli_entry
*e
, struct ast_cli_entry
*ed
)
1416 if (e
->deprecate_cmd
) {
1417 __ast_cli_unregister(e
->deprecate_cmd
, e
);
1420 ast_log(LOG_WARNING
, "Can't remove command that is in use\n");
1422 AST_RWLIST_WRLOCK(&helpers
);
1423 AST_RWLIST_REMOVE(&helpers
, e
, list
);
1424 AST_RWLIST_UNLOCK(&helpers
);
1425 ast_free(e
->_full_cmd
);
1426 e
->_full_cmd
= NULL
;
1428 /* this is a new-style entry. Reset fields and free memory. */
1429 bzero((char **)(e
->cmda
), sizeof(e
->cmda
));
1430 ast_free(e
->command
);
1438 static int __ast_cli_register(struct ast_cli_entry
*e
, struct ast_cli_entry
*ed
)
1440 struct ast_cli_entry
*cur
;
1441 int i
, lf
, ret
= -1;
1443 struct ast_cli_args a
; /* fake argument */
1444 char **dst
= (char **)e
->cmda
; /* need to cast as the entry is readonly */
1447 bzero (&a
, sizeof(a
));
1448 e
->handler(e
, CLI_INIT
, &a
);
1449 /* XXX check that usage and command are filled up */
1450 s
= ast_skip_blanks(e
->command
);
1451 s
= e
->command
= ast_strdup(s
);
1452 for (i
=0; !ast_strlen_zero(s
) && i
< AST_MAX_CMD_LEN
-1; i
++) {
1453 *dst
++ = s
; /* store string */
1454 s
= ast_skip_nonblanks(s
);
1455 if (*s
== '\0') /* we are done */
1458 s
= ast_skip_blanks(s
);
1462 AST_RWLIST_WRLOCK(&helpers
);
1464 if (find_cli(e
->cmda
, 1)) {
1465 ast_log(LOG_WARNING
, "Command '%s' already registered (or something close enough)\n", e
->_full_cmd
);
1468 if (set_full_cmd(e
))
1474 e
->summary
= ed
->summary
;
1475 e
->usage
= ed
->usage
;
1476 /* XXX If command A deprecates command B, and command B deprecates command C...
1477 Do we want to show command A or command B when telling the user to use new syntax?
1478 This currently would show command A.
1479 To show command B, you just need to always use ed->_full_cmd.
1481 e
->_deprecated_by
= S_OR(ed
->_deprecated_by
, ed
->_full_cmd
);
1485 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&helpers
, cur
, list
) {
1486 int len
= cur
->cmdlen
;
1489 if (strncasecmp(e
->_full_cmd
, cur
->_full_cmd
, len
) < 0) {
1490 AST_RWLIST_INSERT_BEFORE_CURRENT(e
, list
);
1494 AST_RWLIST_TRAVERSE_SAFE_END
;
1497 AST_RWLIST_INSERT_TAIL(&helpers
, e
, list
);
1498 ret
= 0; /* success */
1501 AST_RWLIST_UNLOCK(&helpers
);
1503 if (e
->deprecate_cmd
) {
1504 /* This command deprecates another command. Register that one also. */
1505 __ast_cli_register(e
->deprecate_cmd
, e
);
1511 /* wrapper function, so we can unregister deprecated commands recursively */
1512 int ast_cli_unregister(struct ast_cli_entry
*e
)
1514 return __ast_cli_unregister(e
, NULL
);
1517 /* wrapper function, so we can register deprecated commands recursively */
1518 int ast_cli_register(struct ast_cli_entry
*e
)
1520 return __ast_cli_register(e
, NULL
);
1524 * register/unregister an array of entries.
1526 int ast_cli_register_multiple(struct ast_cli_entry
*e
, int len
)
1530 for (i
= 0; i
< len
; i
++)
1531 res
|= ast_cli_register(e
+ i
);
1536 int ast_cli_unregister_multiple(struct ast_cli_entry
*e
, int len
)
1540 for (i
= 0; i
< len
; i
++)
1541 res
|= ast_cli_unregister(e
+ i
);
1547 /*! \brief helper for final part of handle_help
1548 * if locked = 1, assume the list is already locked
1550 static char *help1(int fd
, char *match
[], int locked
)
1552 char matchstr
[80] = "";
1553 struct ast_cli_entry
*e
= NULL
;
1558 ast_join(matchstr
, sizeof(matchstr
), match
);
1559 len
= strlen(matchstr
);
1562 AST_RWLIST_RDLOCK(&helpers
);
1563 while ( (e
= cli_next(e
)) ) {
1564 /* Hide commands that start with '_' */
1565 if (e
->_full_cmd
[0] == '_')
1567 /* Hide commands that are marked as deprecated. */
1570 if (match
&& strncasecmp(matchstr
, e
->_full_cmd
, len
))
1572 ast_cli(fd
, "%30.30s %s\n", e
->_full_cmd
, S_OR(e
->summary
, "<no description available>"));
1576 AST_RWLIST_UNLOCK(&helpers
);
1577 if (!found
&& matchstr
[0])
1578 ast_cli(fd
, "No such command '%s'.\n", matchstr
);
1582 static char *handle_help(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
1585 struct ast_cli_entry
*my_e
;
1586 char *res
= CLI_SUCCESS
;
1588 if (cmd
== CLI_INIT
) {
1589 e
->command
= "help";
1591 "Usage: help [topic]\n"
1592 " When called with a topic as an argument, displays usage\n"
1593 " information on the given command. If called without a\n"
1594 " topic, it provides a list of commands.\n";
1597 } else if (cmd
== CLI_GENERATE
) {
1598 /* skip first 4 or 5 chars, "help " */
1599 int l
= strlen(a
->line
);
1603 /* XXX watch out, should stop to the non-generator parts */
1604 return __ast_cli_generator(a
->line
+ l
, a
->word
, a
->n
, 0);
1607 return help1(a
->fd
, NULL
, 0);
1609 AST_RWLIST_RDLOCK(&helpers
);
1610 my_e
= find_cli(a
->argv
+ 1, 1); /* try exact match first */
1612 res
= help1(a
->fd
, a
->argv
+ 1, 1 /* locked */);
1613 AST_RWLIST_UNLOCK(&helpers
);
1617 ast_cli(a
->fd
, "%s", my_e
->usage
);
1619 ast_join(fullcmd
, sizeof(fullcmd
), a
->argv
+1);
1620 ast_cli(a
->fd
, "No help text available for '%s'.\n", fullcmd
);
1622 AST_RWLIST_UNLOCK(&helpers
);
1626 static char *parse_args(const char *s
, int *argc
, char *argv
[], int max
, int *trailingwhitespace
)
1635 if (trailingwhitespace
== NULL
)
1636 trailingwhitespace
= &dummy
;
1637 *trailingwhitespace
= 0;
1638 if (s
== NULL
) /* invalid, though! */
1640 /* make a copy to store the parsed string */
1641 if (!(dup
= ast_strdup(s
)))
1645 /* scan the original string copying into cur when needed */
1648 ast_log(LOG_WARNING
, "Too many arguments, truncating at %s\n", s
);
1651 if (*s
== '"' && !escaped
) {
1653 if (quoted
&& whitespace
) {
1654 /* start a quoted string from previous whitespace: new argument */
1658 } else if ((*s
== ' ' || *s
== '\t') && !(quoted
|| escaped
)) {
1659 /* If we are not already in whitespace, and not in a quoted string or
1660 processing an escape sequence, and just entered whitespace, then
1661 finalize the previous argument and remember that we are in whitespace
1667 } else if (*s
== '\\' && !escaped
) {
1671 /* we leave whitespace, and are not quoted. So it's a new argument */
1679 /* Null terminate */
1681 /* XXX put a NULL in the last argument, because some functions that take
1682 * the array may want a null-terminated array.
1683 * argc still reflects the number of non-NULL entries.
1687 *trailingwhitespace
= whitespace
;
1691 /*! \brief Return the number of unique matches for the generator */
1692 int ast_cli_generatornummatches(const char *text
, const char *word
)
1694 int matches
= 0, i
= 0;
1695 char *buf
= NULL
, *oldbuf
= NULL
;
1697 while ((buf
= ast_cli_generator(text
, word
, i
++))) {
1698 if (!oldbuf
|| strcmp(buf
,oldbuf
))
1709 char **ast_cli_completion_matches(const char *text
, const char *word
)
1711 char **match_list
= NULL
, *retstr
, *prevstr
;
1712 size_t match_list_len
, max_equal
, which
, i
;
1715 /* leave entry 0 free for the longest common substring */
1717 while ((retstr
= ast_cli_generator(text
, word
, matches
)) != NULL
) {
1718 if (matches
+ 1 >= match_list_len
) {
1719 match_list_len
<<= 1;
1720 if (!(match_list
= ast_realloc(match_list
, match_list_len
* sizeof(*match_list
))))
1723 match_list
[++matches
] = retstr
;
1727 return match_list
; /* NULL */
1729 /* Find the longest substring that is common to all results
1730 * (it is a candidate for completion), and store a copy in entry 0.
1732 prevstr
= match_list
[1];
1733 max_equal
= strlen(prevstr
);
1734 for (which
= 2; which
<= matches
; which
++) {
1735 for (i
= 0; i
< max_equal
&& toupper(prevstr
[i
]) == toupper(match_list
[which
][i
]); i
++)
1740 if (!(retstr
= ast_malloc(max_equal
+ 1)))
1743 ast_copy_string(retstr
, match_list
[1], max_equal
+ 1);
1744 match_list
[0] = retstr
;
1746 /* ensure that the array is NULL terminated */
1747 if (matches
+ 1 >= match_list_len
) {
1748 if (!(match_list
= ast_realloc(match_list
, (match_list_len
+ 1) * sizeof(*match_list
))))
1751 match_list
[matches
+ 1] = NULL
;
1756 /*! \brief returns true if there are more words to match */
1757 static int more_words (char * const *dst
)
1760 for (i
= 0; dst
[i
]; i
++) {
1761 if (dst
[i
][0] != '[')
1768 * generate the entry at position 'state'
1770 static char *__ast_cli_generator(const char *text
, const char *word
, int state
, int lock
)
1772 char *argv
[AST_MAX_ARGS
];
1773 struct ast_cli_entry
*e
= NULL
;
1774 int x
= 0, argindex
, matchlen
;
1777 char matchstr
[80] = "";
1779 /* Split the argument into an array of words */
1780 char *dup
= parse_args(text
, &x
, argv
, sizeof(argv
) / sizeof(argv
[0]), &tws
);
1782 if (!dup
) /* malloc error */
1785 /* Compute the index of the last argument (could be an empty string) */
1786 argindex
= (!ast_strlen_zero(word
) && x
>0) ? x
-1 : x
;
1788 /* rebuild the command, ignore terminating white space and flatten space */
1789 ast_join(matchstr
, sizeof(matchstr
)-1, argv
);
1790 matchlen
= strlen(matchstr
);
1792 strcat(matchstr
, " "); /* XXX */
1797 AST_RWLIST_RDLOCK(&helpers
);
1798 while ( (e
= cli_next(e
)) ) {
1799 /* XXX repeated code */
1800 int src
= 0, dst
= 0, n
= 0;
1802 if (e
->command
[0] == '_')
1806 * Try to match words, up to and excluding the last word, which
1807 * is either a blank or something that we want to extend.
1809 for (;src
< argindex
; dst
++, src
+= n
) {
1810 n
= word_match(argv
[src
], e
->cmda
[dst
]);
1815 if (src
!= argindex
&& more_words(e
->cmda
+ dst
)) /* not a match */
1817 ret
= is_prefix(argv
[src
], e
->cmda
[dst
], state
- matchnum
, &n
);
1818 matchnum
+= n
; /* this many matches here */
1821 * argv[src] is a valid prefix of the next word in this
1822 * command. If this is also the correct entry, return it.
1824 if (matchnum
> state
)
1828 } else if (ast_strlen_zero(e
->cmda
[dst
])) {
1830 * This entry is a prefix of the command string entered
1831 * (only one entry in the list should have this property).
1832 * Run the generator if one is available. In any case we are done.
1834 if (e
->handler
) { /* new style command */
1835 struct ast_cli_args a
= {
1836 .line
= matchstr
, .word
= word
,
1838 .n
= state
- matchnum
};
1839 ret
= e
->handler(e
, CLI_GENERATE
, &a
);
1846 AST_RWLIST_UNLOCK(&helpers
);
1851 char *ast_cli_generator(const char *text
, const char *word
, int state
)
1853 return __ast_cli_generator(text
, word
, state
, 1);
1856 int ast_cli_command(int fd
, const char *s
)
1858 char *args
[AST_MAX_ARGS
+ 1];
1859 struct ast_cli_entry
*e
;
1861 char *dup
= parse_args(s
, &x
, args
+ 1, AST_MAX_ARGS
, NULL
);
1862 char *retval
= NULL
;
1863 struct ast_cli_args a
= {
1864 .fd
= fd
, .argc
= x
, .argv
= args
+1 };
1869 if (x
< 1) /* We need at least one entry, otherwise ignore */
1872 AST_RWLIST_RDLOCK(&helpers
);
1873 e
= find_cli(args
+ 1, 0);
1875 ast_atomic_fetchadd_int(&e
->inuse
, 1);
1876 AST_RWLIST_UNLOCK(&helpers
);
1878 ast_cli(fd
, "No such command '%s' (type 'help' for help)\n", find_best(args
+ 1));
1882 * Within the handler, argv[-1] contains a pointer to the ast_cli_entry.
1883 * Remember that the array returned by parse_args is NULL-terminated.
1885 args
[0] = (char *)e
;
1887 retval
= e
->handler(e
, CLI_HANDLER
, &a
);
1889 if (retval
== CLI_SHOWUSAGE
) {
1890 ast_cli(fd
, "%s", S_OR(e
->usage
, "Invalid usage, but no usage information available.\n"));
1891 AST_RWLIST_RDLOCK(&helpers
);
1893 ast_cli(fd
, "The '%s' command is deprecated and will be removed in a future release. Please use '%s' instead.\n", e
->_full_cmd
, e
->_deprecated_by
);
1894 AST_RWLIST_UNLOCK(&helpers
);
1896 if (retval
== CLI_FAILURE
)
1897 ast_cli(fd
, "Command '%s' failed.\n", s
);
1898 AST_RWLIST_RDLOCK(&helpers
);
1899 if (e
->deprecated
== 1) {
1900 ast_cli(fd
, "The '%s' command is deprecated and will be removed in a future release. Please use '%s' instead.\n", e
->_full_cmd
, e
->_deprecated_by
);
1903 AST_RWLIST_UNLOCK(&helpers
);
1905 ast_atomic_fetchadd_int(&e
->inuse
, -1);
1911 int ast_cli_command_multiple(int fd
, size_t size
, const char *s
)
1914 int x
, y
= 0, count
= 0;
1916 for (x
= 0; x
< size
; x
++) {
1920 ast_cli_command(fd
, cmd
);