add ExtenSpy variant of ChanSpy
[asterisk-bristuff.git] / cli.c
blob6afd56d5e703b66b57b13288abebb16118973608
1 /*
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.
19 /*! \file
21 * \brief Standard Command Line Interface
23 * \author Mark Spencer <markster@digium.com>
26 #include "asterisk.h"
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include <unistd.h>
31 #include <stdlib.h>
32 #include <sys/signal.h>
33 #include <stdio.h>
34 #include <signal.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <regex.h>
39 #include "asterisk/logger.h"
40 #include "asterisk/options.h"
41 #include "asterisk/cli.h"
42 #include "asterisk/linkedlists.h"
43 #define MOD_LOADER
44 #include "asterisk/module.h"
45 #include "asterisk/pbx.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/utils.h"
48 #include "asterisk/app.h"
49 #include "asterisk/lock.h"
50 #include "editline/readline/readline.h"
52 extern unsigned long global_fin, global_fout;
54 static pthread_key_t ast_cli_buf_key;
55 static pthread_once_t ast_cli_buf_once = PTHREAD_ONCE_INIT;
57 /*! \brief Initial buffer size for resulting strings in ast_cli() */
58 #define AST_CLI_MAXSTRLEN 256
60 #ifdef __AST_DEBUG_MALLOC
61 static void FREE(void *ptr)
63 free(ptr);
65 #else
66 #define FREE free
67 #endif
69 static void ast_cli_buf_key_create(void)
71 pthread_key_create(&ast_cli_buf_key, FREE);
74 void ast_cli(int fd, char *fmt, ...)
76 struct {
77 size_t len;
78 char str[0];
79 } *buf;
80 int res;
81 va_list ap;
83 pthread_once(&ast_cli_buf_once, ast_cli_buf_key_create);
84 if (!(buf = pthread_getspecific(ast_cli_buf_key))) {
85 if (!(buf = ast_malloc(AST_CLI_MAXSTRLEN + sizeof(*buf))))
86 return;
87 buf->len = AST_CLI_MAXSTRLEN;
88 pthread_setspecific(ast_cli_buf_key, buf);
91 va_start(ap, fmt);
92 res = vsnprintf(buf->str, buf->len, fmt, ap);
93 while (res >= buf->len) {
94 if (!(buf = ast_realloc(buf, (buf->len * 2) + sizeof(*buf)))) {
95 va_end(ap);
96 return;
98 buf->len *= 2;
99 pthread_setspecific(ast_cli_buf_key, buf);
100 va_end(ap);
101 va_start(ap, fmt);
102 res = vsnprintf(buf->str, buf->len, fmt, ap);
104 va_end(ap);
106 if (res > 0)
107 ast_carefulwrite(fd, buf->str, strlen(buf->str), 100);
110 static AST_LIST_HEAD_STATIC(helpers, ast_cli_entry);
112 static char load_help[] =
113 "Usage: load <module name>\n"
114 " Loads the specified module into Asterisk.\n";
116 static char unload_help[] =
117 "Usage: unload [-f|-h] <module name>\n"
118 " Unloads the specified module from Asterisk. The -f\n"
119 " option causes the module to be unloaded even if it is\n"
120 " in use (may cause a crash) and the -h module causes the\n"
121 " module to be unloaded even if the module says it cannot, \n"
122 " which almost always will cause a crash.\n";
124 static char help_help[] =
125 "Usage: help [topic]\n"
126 " When called with a topic as an argument, displays usage\n"
127 " information on the given command. If called without a\n"
128 " topic, it provides a list of commands.\n";
130 static char chanlist_help[] =
131 "Usage: show channels [concise|verbose]\n"
132 " Lists currently defined channels and some information about them. If\n"
133 " 'concise' is specified, the format is abridged and in a more easily\n"
134 " machine parsable format. If 'verbose' is specified, the output includes\n"
135 " more and longer fields.\n";
137 static char reload_help[] =
138 "Usage: reload [module ...]\n"
139 " Reloads configuration files for all listed modules which support\n"
140 " reloading, or for all supported modules if none are listed.\n";
142 static char set_verbose_help[] =
143 "Usage: set verbose <level>\n"
144 " Sets level of verbose messages to be displayed. 0 means\n"
145 " no messages should be displayed. Equivalent to -v[v[v...]]\n"
146 " on startup\n";
148 static char set_debug_help[] =
149 "Usage: set debug <level>\n"
150 " Sets level of core debug messages to be displayed. 0 means\n"
151 " no messages should be displayed. Equivalent to -d[d[d...]]\n"
152 " on startup.\n";
154 static char logger_mute_help[] =
155 "Usage: logger mute\n"
156 " Disables logging output to the current console, making it possible to\n"
157 " gather information without being disturbed by scrolling lines.\n";
159 static char softhangup_help[] =
160 "Usage: soft hangup <channel>\n"
161 " Request that a channel be hung up. The hangup takes effect\n"
162 " the next time the driver reads or writes from the channel\n";
164 static char group_show_channels_help[] =
165 "Usage: group show channels [pattern]\n"
166 " Lists all currently active channels with channel group(s) specified.\n"
167 " Optional regular expression pattern is matched to group names for each\n"
168 " channel.\n";
170 static int handle_load(int fd, int argc, char *argv[])
172 if (argc != 2)
173 return RESULT_SHOWUSAGE;
174 if (ast_load_resource(argv[1])) {
175 ast_cli(fd, "Unable to load module %s\n", argv[1]);
176 return RESULT_FAILURE;
178 return RESULT_SUCCESS;
181 static int handle_reload(int fd, int argc, char *argv[])
183 int x;
184 int res;
185 if (argc < 1)
186 return RESULT_SHOWUSAGE;
187 if (argc > 1) {
188 for (x=1;x<argc;x++) {
189 res = ast_module_reload(argv[x]);
190 switch(res) {
191 case 0:
192 ast_cli(fd, "No such module '%s'\n", argv[x]);
193 break;
194 case 1:
195 ast_cli(fd, "Module '%s' does not support reload\n", argv[x]);
196 break;
199 } else
200 ast_module_reload(NULL);
201 return RESULT_SUCCESS;
204 static int handle_set_verbose(int fd, int argc, char *argv[])
206 int val = 0;
207 int oldval = option_verbose;
209 /* "set verbose [atleast] N" */
210 if (argc == 3)
211 option_verbose = atoi(argv[2]);
212 else if (argc == 4) {
213 if (strcasecmp(argv[2], "atleast"))
214 return RESULT_SHOWUSAGE;
215 val = atoi(argv[3]);
216 if (val > option_verbose)
217 option_verbose = val;
218 } else
219 return RESULT_SHOWUSAGE;
220 if (oldval != option_verbose && option_verbose > 0)
221 ast_cli(fd, "Verbosity was %d and is now %d\n", oldval, option_verbose);
222 else if (oldval > 0 && option_verbose > 0)
223 ast_cli(fd, "Verbosity is at least %d\n", option_verbose);
224 else if (oldval > 0 && option_verbose == 0)
225 ast_cli(fd, "Verbosity is now OFF\n");
226 return RESULT_SUCCESS;
229 static int handle_set_debug(int fd, int argc, char *argv[])
231 int val = 0;
232 int oldval = option_debug;
234 /* "set debug [atleast] N" */
235 if (argc == 3)
236 option_debug = atoi(argv[2]);
237 else if (argc == 4) {
238 if (strcasecmp(argv[2], "atleast"))
239 return RESULT_SHOWUSAGE;
240 val = atoi(argv[3]);
241 if (val > option_debug)
242 option_debug = val;
243 } else
244 return RESULT_SHOWUSAGE;
245 if (oldval != option_debug && option_debug > 0)
246 ast_cli(fd, "Core debug was %d and is now %d\n", oldval, option_debug);
247 else if (oldval > 0 && option_debug > 0)
248 ast_cli(fd, "Core debug is at least %d\n", option_debug);
249 else if (oldval > 0 && option_debug == 0)
250 ast_cli(fd, "Core debug is now OFF\n");
251 return RESULT_SUCCESS;
254 static int handle_logger_mute(int fd, int argc, char *argv[])
256 if (argc != 2)
257 return RESULT_SHOWUSAGE;
258 ast_console_toggle_mute(fd);
259 return RESULT_SUCCESS;
262 static int handle_unload(int fd, int argc, char *argv[])
264 int x;
265 int force=AST_FORCE_SOFT;
266 if (argc < 2)
267 return RESULT_SHOWUSAGE;
268 for (x=1;x<argc;x++) {
269 if (argv[x][0] == '-') {
270 switch(argv[x][1]) {
271 case 'f':
272 force = AST_FORCE_FIRM;
273 break;
274 case 'h':
275 force = AST_FORCE_HARD;
276 break;
277 default:
278 return RESULT_SHOWUSAGE;
280 } else if (x != argc - 1)
281 return RESULT_SHOWUSAGE;
282 else if (ast_unload_resource(argv[x], force)) {
283 ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
284 return RESULT_FAILURE;
287 return RESULT_SUCCESS;
290 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
291 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
293 AST_MUTEX_DEFINE_STATIC(climodentrylock);
294 static int climodentryfd = -1;
296 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
298 /* Comparing the like with the module */
299 if (strcasestr(module, like) ) {
300 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
301 return 1;
303 return 0;
306 static char modlist_help[] =
307 "Usage: show modules [like keyword]\n"
308 " Shows Asterisk modules currently in use, and usage statistics.\n";
310 static char uptime_help[] =
311 "Usage: show uptime [seconds]\n"
312 " Shows Asterisk uptime information.\n"
313 " The seconds word returns the uptime in seconds only.\n";
315 static void print_uptimestr(int fd, time_t timeval, const char *prefix, int printsec)
317 int x; /* the main part - years, weeks, etc. */
318 char timestr[256]="", *s = timestr;
319 size_t maxbytes = sizeof(timestr);
321 #define SECOND (1)
322 #define MINUTE (SECOND*60)
323 #define HOUR (MINUTE*60)
324 #define DAY (HOUR*24)
325 #define WEEK (DAY*7)
326 #define YEAR (DAY*365)
327 #define ESS(x) ((x == 1) ? "" : "s") /* plural suffix */
328 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
329 if (timeval < 0) /* invalid, nothing to show */
330 return;
331 if (printsec) { /* plain seconds output */
332 ast_build_string(&s, &maxbytes, "%lu", (u_long)timeval);
333 timeval = 0; /* bypass the other cases */
335 if (timeval > YEAR) {
336 x = (timeval / YEAR);
337 timeval -= (x * YEAR);
338 ast_build_string(&s, &maxbytes, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval));
340 if (timeval > WEEK) {
341 x = (timeval / WEEK);
342 timeval -= (x * WEEK);
343 ast_build_string(&s, &maxbytes, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval));
345 if (timeval > DAY) {
346 x = (timeval / DAY);
347 timeval -= (x * DAY);
348 ast_build_string(&s, &maxbytes, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval));
350 if (timeval > HOUR) {
351 x = (timeval / HOUR);
352 timeval -= (x * HOUR);
353 ast_build_string(&s, &maxbytes, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval));
355 if (timeval > MINUTE) {
356 x = (timeval / MINUTE);
357 timeval -= (x * MINUTE);
358 ast_build_string(&s, &maxbytes, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval));
360 x = timeval;
361 if (x > 0)
362 ast_build_string(&s, &maxbytes, "%d second%s ", x, ESS(x));
363 if (timestr[0] != '\0')
364 ast_cli(fd, "%s: %s\n", prefix, timestr);
367 static int handle_showuptime(int fd, int argc, char *argv[])
369 /* 'show uptime [seconds]' */
370 time_t curtime = time(NULL);
371 int printsec = (argc == 3 && !strcasecmp(argv[2],"seconds"));
373 if (argc != 2 && !printsec)
374 return RESULT_SHOWUSAGE;
375 if (ast_startuptime)
376 print_uptimestr(fd, curtime - ast_startuptime, "System uptime", printsec);
377 if (ast_lastreloadtime)
378 print_uptimestr(fd, curtime - ast_lastreloadtime, "Last reload", printsec);
379 return RESULT_SUCCESS;
382 static int handle_modlist(int fd, int argc, char *argv[])
384 char *like = "";
385 if (argc == 3)
386 return RESULT_SHOWUSAGE;
387 else if (argc >= 4) {
388 if (strcmp(argv[2],"like"))
389 return RESULT_SHOWUSAGE;
390 like = argv[3];
393 ast_mutex_lock(&climodentrylock);
394 climodentryfd = fd; /* global, protected by climodentrylock */
395 ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
396 ast_cli(fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
397 climodentryfd = -1;
398 ast_mutex_unlock(&climodentrylock);
399 return RESULT_SUCCESS;
401 #undef MODLIST_FORMAT
402 #undef MODLIST_FORMAT2
404 static int handle_chanlist(int fd, int argc, char *argv[])
406 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
407 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
408 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s\n"
409 #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"
410 #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"
412 struct ast_channel *c = NULL;
413 char durbuf[10] = "-";
414 char locbuf[40];
415 char appdata[40];
416 int duration;
417 int durh, durm, durs;
418 int numchans = 0, concise = 0, verbose = 0;
420 concise = (argc == 3 && (!strcasecmp(argv[2],"concise")));
421 verbose = (argc == 3 && (!strcasecmp(argv[2],"verbose")));
423 if (argc < 2 || argc > 3 || (argc == 3 && !concise && !verbose))
424 return RESULT_SHOWUSAGE;
426 if (!concise && !verbose)
427 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
428 else if (verbose)
429 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
430 "CallerID", "Duration", "Accountcode", "BridgedTo");
432 while ((c = ast_channel_walk_locked(c)) != NULL) {
433 struct ast_channel *bc = ast_bridged_channel(c);
434 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
435 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
436 if (verbose) {
437 durh = duration / 3600;
438 durm = (duration % 3600) / 60;
439 durs = duration % 60;
440 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
441 } else {
442 snprintf(durbuf, sizeof(durbuf), "%d", duration);
444 } else {
445 durbuf[0] = '\0';
447 if (concise) {
448 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
449 c->appl ? c->appl : "(None)",
450 S_OR(c->data, ""), /* XXX different from verbose ? */
451 S_OR(c->cid.cid_num, ""),
452 S_OR(c->accountcode, ""),
453 c->amaflags,
454 durbuf,
455 bc ? bc->name : "(None)");
456 } else if (verbose) {
457 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
458 c->appl ? c->appl : "(None)",
459 c->data ? S_OR(c->data, "(Empty)" ): "(None)",
460 S_OR(c->cid.cid_num, ""),
461 durbuf,
462 S_OR(c->accountcode, ""),
463 bc ? bc->name : "(None)");
464 } else {
465 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
466 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
467 else
468 strcpy(locbuf, "(None)");
469 if (c->appl)
470 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, c->data ? c->data : "");
471 else
472 strcpy(appdata, "(None)");
473 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
475 numchans++;
476 ast_channel_unlock(c);
478 if (!concise) {
479 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
480 if (option_maxcalls)
481 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
482 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
483 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
484 else
485 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
487 return RESULT_SUCCESS;
489 #undef FORMAT_STRING
490 #undef FORMAT_STRING2
491 #undef CONCISE_FORMAT_STRING
492 #undef VERBOSE_FORMAT_STRING
493 #undef VERBOSE_FORMAT_STRING2
496 static char showchan_help[] =
497 "Usage: show channel <channel>\n"
498 " Shows lots of information about the specified channel.\n";
500 static char debugchan_help[] =
501 "Usage: debug channel <channel>\n"
502 " Enables debugging on a specific channel.\n";
504 static char debuglevel_help[] =
505 "Usage: debug level <level> [filename]\n"
506 " Set debug to specified level (0 to disable). If filename\n"
507 "is specified, debugging will be limited to just that file.\n";
509 static char nodebugchan_help[] =
510 "Usage: no debug channel <channel>\n"
511 " Disables debugging on a specific channel.\n";
513 static char commandcomplete_help[] =
514 "Usage: _command complete \"<line>\" text state\n"
515 " This function is used internally to help with command completion and should.\n"
516 " never be called by the user directly.\n";
518 static char commandnummatches_help[] =
519 "Usage: _command nummatches \"<line>\" text \n"
520 " This function is used internally to help with command completion and should.\n"
521 " never be called by the user directly.\n";
523 static char commandmatchesarray_help[] =
524 "Usage: _command matchesarray \"<line>\" text \n"
525 " This function is used internally to help with command completion and should.\n"
526 " never be called by the user directly.\n";
528 static int handle_softhangup(int fd, int argc, char *argv[])
530 struct ast_channel *c=NULL;
531 if (argc != 3)
532 return RESULT_SHOWUSAGE;
533 c = ast_get_channel_by_name_locked(argv[2]);
534 if (c) {
535 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
536 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
537 ast_channel_unlock(c);
538 } else
539 ast_cli(fd, "%s is not a known channel\n", argv[2]);
540 return RESULT_SUCCESS;
543 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
545 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
547 char *buf, *obuf;
548 int buflen = 2048;
549 int len = 0;
550 char **matches;
551 int x, matchlen;
553 if (argc != 4)
554 return RESULT_SHOWUSAGE;
555 if (!(buf = ast_malloc(buflen)))
556 return RESULT_FAILURE;
557 buf[len] = '\0';
558 matches = ast_cli_completion_matches(argv[2], argv[3]);
559 if (matches) {
560 for (x=0; matches[x]; x++) {
561 matchlen = strlen(matches[x]) + 1;
562 if (len + matchlen >= buflen) {
563 buflen += matchlen * 3;
564 obuf = buf;
565 if (!(buf = ast_realloc(obuf, buflen)))
566 /* Memory allocation failure... Just free old buffer and be done */
567 free(obuf);
569 if (buf)
570 len += sprintf( buf + len, "%s ", matches[x]);
571 free(matches[x]);
572 matches[x] = NULL;
574 free(matches);
577 if (buf) {
578 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
579 free(buf);
580 } else
581 ast_cli(fd, "NULL\n");
583 return RESULT_SUCCESS;
588 static int handle_commandnummatches(int fd, int argc, char *argv[])
590 int matches = 0;
592 if (argc != 4)
593 return RESULT_SHOWUSAGE;
595 matches = ast_cli_generatornummatches(argv[2], argv[3]);
597 ast_cli(fd, "%d", matches);
599 return RESULT_SUCCESS;
602 static int handle_commandcomplete(int fd, int argc, char *argv[])
604 char *buf;
606 if (argc != 5)
607 return RESULT_SHOWUSAGE;
608 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
609 if (buf) {
610 ast_cli(fd, buf);
611 free(buf);
612 } else
613 ast_cli(fd, "NULL\n");
614 return RESULT_SUCCESS;
617 static int handle_debuglevel(int fd, int argc, char *argv[])
619 int newlevel;
620 char *filename = "<any>";
621 if ((argc < 3) || (argc > 4))
622 return RESULT_SHOWUSAGE;
623 if (sscanf(argv[2], "%d", &newlevel) != 1)
624 return RESULT_SHOWUSAGE;
625 option_debug = newlevel;
626 if (argc == 4) {
627 filename = argv[3];
628 ast_copy_string(debug_filename, filename, sizeof(debug_filename));
629 } else {
630 debug_filename[0] = '\0';
632 ast_cli(fd, "Debugging level set to %d, file '%s'\n", newlevel, filename);
633 return RESULT_SUCCESS;
636 /* XXX todo: merge next two functions!!! */
637 static int handle_debugchan(int fd, int argc, char *argv[])
639 struct ast_channel *c=NULL;
640 int is_all;
642 /* 'debug channel {all|chan_id}' */
643 if (argc != 3)
644 return RESULT_SHOWUSAGE;
646 is_all = !strcasecmp("all", argv[2]);
647 if (is_all) {
648 global_fin |= DEBUGCHAN_FLAG;
649 global_fout |= DEBUGCHAN_FLAG;
650 c = ast_channel_walk_locked(NULL);
651 } else {
652 c = ast_get_channel_by_name_locked(argv[2]);
653 if (c == NULL)
654 ast_cli(fd, "No such channel %s\n", argv[2]);
656 while (c) {
657 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
658 c->fin |= DEBUGCHAN_FLAG;
659 c->fout |= DEBUGCHAN_FLAG;
660 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
662 ast_channel_unlock(c);
663 if (!is_all)
664 break;
665 c = ast_channel_walk_locked(c);
667 ast_cli(fd, "Debugging on new channels is enabled\n");
668 return RESULT_SUCCESS;
671 static int handle_nodebugchan(int fd, int argc, char *argv[])
673 struct ast_channel *c=NULL;
674 int is_all;
675 /* 'no debug channel {all|chan_id}' */
676 if (argc != 4)
677 return RESULT_SHOWUSAGE;
678 is_all = !strcasecmp("all", argv[3]);
679 if (is_all) {
680 global_fin &= ~DEBUGCHAN_FLAG;
681 global_fout &= ~DEBUGCHAN_FLAG;
682 c = ast_channel_walk_locked(NULL);
683 } else {
684 c = ast_get_channel_by_name_locked(argv[3]);
685 if (c == NULL)
686 ast_cli(fd, "No such channel %s\n", argv[3]);
688 while(c) {
689 if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
690 c->fin &= ~DEBUGCHAN_FLAG;
691 c->fout &= ~DEBUGCHAN_FLAG;
692 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
694 ast_channel_unlock(c);
695 if (!is_all)
696 break;
697 c = ast_channel_walk_locked(c);
699 ast_cli(fd, "Debugging on new channels is disabled\n");
700 return RESULT_SUCCESS;
703 static int handle_showchan(int fd, int argc, char *argv[])
705 struct ast_channel *c=NULL;
706 struct timeval now;
707 char buf[2048];
708 char cdrtime[256];
709 char nf[256], wf[256], rf[256];
710 long elapsed_seconds=0;
711 int hour=0, min=0, sec=0;
713 if (argc != 3)
714 return RESULT_SHOWUSAGE;
715 now = ast_tvnow();
716 c = ast_get_channel_by_name_locked(argv[2]);
717 if (!c) {
718 ast_cli(fd, "%s is not a known channel\n", argv[2]);
719 return RESULT_SUCCESS;
721 if(c->cdr) {
722 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
723 hour = elapsed_seconds / 3600;
724 min = (elapsed_seconds % 3600) / 60;
725 sec = elapsed_seconds % 60;
726 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
727 } else
728 strcpy(cdrtime, "N/A");
729 ast_cli(fd,
730 " -- General --\n"
731 " Name: %s\n"
732 " Type: %s\n"
733 " UniqueID: %s\n"
734 " Caller ID: %s\n"
735 " Caller ID Name: %s\n"
736 " DNID Digits: %s\n"
737 " State: %s (%d)\n"
738 " Rings: %d\n"
739 " NativeFormats: %s\n"
740 " WriteFormat: %s\n"
741 " ReadFormat: %s\n"
742 " WriteTranscode: %s\n"
743 " ReadTranscode: %s\n"
744 "1st File Descriptor: %d\n"
745 " Frames in: %d%s\n"
746 " Frames out: %d%s\n"
747 " Time to Hangup: %ld\n"
748 " Elapsed Time: %s\n"
749 " Direct Bridge: %s\n"
750 "Indirect Bridge: %s\n"
751 " -- PBX --\n"
752 " Context: %s\n"
753 " Extension: %s\n"
754 " Priority: %d\n"
755 " Call Group: %d\n"
756 " Pickup Group: %d\n"
757 " Application: %s\n"
758 " Data: %s\n"
759 " Blocking in: %s\n",
760 c->name, c->tech->type, c->uniqueid,
761 S_OR(c->cid.cid_num, "(N/A)"),
762 S_OR(c->cid.cid_name, "(N/A)"),
763 S_OR(c->cid.cid_dnid, "(N/A)"), ast_state2str(c->_state), c->_state, c->rings,
764 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
765 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
766 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
767 c->writetrans ? "Yes" : "No",
768 c->readtrans ? "Yes" : "No",
769 c->fds[0],
770 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
771 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
772 (long)c->whentohangup,
773 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
774 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
775 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
776 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
778 if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
779 ast_cli(fd," Variables:\n%s\n",buf);
780 if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
781 ast_cli(fd," CDR Variables:\n%s\n",buf);
783 ast_channel_unlock(c);
784 return RESULT_SUCCESS;
788 * helper function to generate CLI matches from a fixed set of values.
789 * A NULL word is acceptable.
791 char *ast_cli_complete(const char *word, char *const choices[], int state)
793 int i, which = 0, len;
794 len = ast_strlen_zero(word) ? 0 : strlen(word);
796 for (i = 0; choices[i]; i++) {
797 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
798 return ast_strdup(choices[i]);
800 return NULL;
803 static char *complete_show_channels(const char *line, const char *word, int pos, int state)
805 static char *choices[] = { "concise", "verbose", NULL };
807 return (pos != 2) ? NULL : ast_cli_complete(word, choices, state);
810 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
812 struct ast_channel *c = NULL;
813 int which = 0;
814 int wordlen;
815 char notfound = '\0';
816 char *ret = &notfound; /* so NULL can break the loop */
818 if (pos != rpos)
819 return NULL;
821 wordlen = strlen(word);
823 while (ret == &notfound && (c = ast_channel_walk_locked(c))) {
824 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
825 ret = ast_strdup(c->name);
826 ast_channel_unlock(c);
828 return ret == &notfound ? NULL : ret;
831 static char *complete_ch_3(const char *line, const char *word, int pos, int state)
833 return ast_complete_channels(line, word, pos, state, 2);
836 static char *complete_ch_4(const char *line, const char *word, int pos, int state)
838 return ast_complete_channels(line, word, pos, state, 3);
841 static char *complete_mod_2(const char *line, const char *word, int pos, int state)
843 return ast_module_helper(line, word, pos, state, 1, 1);
846 static char *complete_mod_4(const char *line, const char *word, int pos, int state)
848 return ast_module_helper(line, word, pos, state, 3, 0);
851 static char *complete_fn(const char *line, const char *word, int pos, int state)
853 char *c;
854 char filename[256];
856 if (pos != 1)
857 return NULL;
859 if (word[0] == '/')
860 ast_copy_string(filename, word, sizeof(filename));
861 else
862 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
864 c = filename_completion_function(filename, state);
866 if (c && word[0] != '/')
867 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
869 return c ? strdup(c) : c;
872 static int group_show_channels(int fd, int argc, char *argv[])
874 #define FORMAT_STRING "%-25s %-20s %-20s\n"
876 struct ast_channel *c = NULL;
877 int numchans = 0;
878 struct ast_var_t *current;
879 struct varshead *headp;
880 regex_t regexbuf;
881 int havepattern = 0;
883 if (argc < 3 || argc > 4)
884 return RESULT_SHOWUSAGE;
886 if (argc == 4) {
887 if (regcomp(&regexbuf, argv[3], REG_EXTENDED | REG_NOSUB))
888 return RESULT_SHOWUSAGE;
889 havepattern = 1;
892 ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
893 while ( (c = ast_channel_walk_locked(c)) != NULL) {
894 headp=&c->varshead;
895 AST_LIST_TRAVERSE(headp,current,entries) {
896 if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
897 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
898 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
899 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
900 numchans++;
902 } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
903 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
904 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
905 numchans++;
909 numchans++;
910 ast_channel_unlock(c);
913 if (havepattern)
914 regfree(&regexbuf);
916 ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
917 return RESULT_SUCCESS;
918 #undef FORMAT_STRING
921 static int handle_help(int fd, int argc, char *argv[]);
923 static char * complete_help(const char *text, const char *word, int pos, int state)
925 /* skip first 4 or 5 chars, "help "*/
926 int l = strlen(text);
928 if (l > 5)
929 l = 5;
930 text += l;
931 /* XXX watch out, should stop to the non-generator parts */
932 return __ast_cli_generator(text, word, state, 0);
935 static struct ast_cli_entry builtins[] = {
936 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
937 { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
938 { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
939 { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
940 { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch_3 },
941 { { "debug", "level", NULL }, handle_debuglevel, "Set global debug level", debuglevel_help },
942 { { "group", "show", "channels", NULL }, group_show_channels, "Show active channels with group(s)", group_show_channels_help},
943 { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help, complete_help },
944 { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
945 { { "logger", "mute", NULL }, handle_logger_mute, "Toggle logging output to a console", logger_mute_help },
946 { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch_4 },
947 { { "reload", NULL }, handle_reload, "Reload configuration", reload_help, complete_mod_2 },
948 { { "set", "debug", NULL }, handle_set_debug, "Set level of debug chattiness", set_debug_help },
949 { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
950 { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch_3 },
951 { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help, complete_show_channels },
952 { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
953 { { "show", "modules", "like", NULL }, handle_modlist, "List modules and info", modlist_help, complete_mod_4 },
954 { { "show", "uptime", NULL }, handle_showuptime, "Show uptime information", uptime_help },
955 { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch_3 },
956 { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
957 { { NULL }, NULL, NULL, NULL }
960 /*! \brief initialize the _full_cmd string in * each of the builtins. */
961 void ast_builtins_init(void)
963 struct ast_cli_entry *e;
965 for (e = builtins; e->cmda[0] != NULL; e++) {
966 char buf[80];
967 ast_join(buf, sizeof(buf), e->cmda);
968 e->_full_cmd = strdup(buf);
969 if (!e->_full_cmd)
970 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
975 * We have two sets of commands: builtins are stored in a
976 * NULL-terminated array of ast_cli_entry, whereas external
977 * commands are in a list.
978 * When navigating, we need to keep two pointers and get
979 * the next one in lexicographic order. For the purpose,
980 * we use a structure.
983 struct cli_iterator {
984 struct ast_cli_entry *builtins;
985 struct ast_cli_entry *helpers;
988 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
990 struct ast_cli_entry *e;
992 if (i->builtins == NULL && i->helpers == NULL) {
993 /* initialize */
994 i->builtins = builtins;
995 i->helpers = AST_LIST_FIRST(&helpers);
997 e = i->builtins; /* temporary */
998 if (!e->cmda[0] || (i->helpers &&
999 strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
1000 /* Use helpers */
1001 e = i->helpers;
1002 if (e)
1003 i->helpers = AST_LIST_NEXT(e, list);
1004 } else { /* use builtin. e is already set */
1005 (i->builtins)++; /* move to next */
1007 return e;
1011 * \brief locate a cli command in the 'helpers' list (which must be locked).
1012 * exact has 3 values:
1013 * 0 returns if the search key is equal or longer than the entry.
1014 * -1 true if the mismatch is on the last word XXX not true!
1015 * 1 true only on complete, exact match.
1017 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1019 int matchlen = -1; /* length of longest match so far */
1020 struct ast_cli_entry *cand = NULL, *e=NULL;
1021 struct cli_iterator i = { NULL, NULL};
1023 while( (e = cli_next(&i)) ) {
1024 int y;
1025 for (y = 0 ; cmds[y] && e->cmda[y]; y++) {
1026 if (strcasecmp(e->cmda[y], cmds[y]))
1027 break;
1029 if (e->cmda[y] == NULL) { /* no more words in candidate */
1030 if (cmds[y] == NULL) /* this is an exact match, cannot do better */
1031 break;
1032 /* here the search key is longer than the candidate */
1033 if (match_type != 0) /* but we look for almost exact match... */
1034 continue; /* so we skip this one. */
1035 /* otherwise we like it (case 0) */
1036 } else { /* still words in candidate */
1037 if (cmds[y] == NULL) /* search key is shorter, not good */
1038 continue;
1039 /* if we get here, both words exist but there is a mismatch */
1040 if (match_type == 0) /* not the one we look for */
1041 continue;
1042 if (match_type == 1) /* not the one we look for */
1043 continue;
1044 if (cmds[y+1] != NULL || e->cmda[y+1] != NULL) /* not the one we look for */
1045 continue;
1046 /* we are in case match_type == -1 and mismatch on last word */
1048 if (cand == NULL || y > matchlen) /* remember the candidate */
1049 cand = e;
1051 return e ? e : cand;
1054 static char *find_best(char *argv[])
1056 static char cmdline[80];
1057 int x;
1058 /* See how close we get, then print the candidate */
1059 char *myargv[AST_MAX_CMD_LEN];
1060 for (x=0;x<AST_MAX_CMD_LEN;x++)
1061 myargv[x]=NULL;
1062 AST_LIST_LOCK(&helpers);
1063 for (x=0;argv[x];x++) {
1064 myargv[x] = argv[x];
1065 if (!find_cli(myargv, -1))
1066 break;
1068 AST_LIST_UNLOCK(&helpers);
1069 ast_join(cmdline, sizeof(cmdline), myargv);
1070 return cmdline;
1073 int ast_cli_unregister(struct ast_cli_entry *e)
1075 if (e->inuse) {
1076 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1077 } else {
1078 AST_LIST_LOCK(&helpers);
1079 AST_LIST_REMOVE(&helpers, e, list);
1080 AST_LIST_UNLOCK(&helpers);
1082 return 0;
1085 int ast_cli_register(struct ast_cli_entry *e)
1087 struct ast_cli_entry *cur;
1088 char fulle[80] ="";
1089 int lf, ret = -1;
1091 ast_join(fulle, sizeof(fulle), e->cmda);
1092 AST_LIST_LOCK(&helpers);
1094 if (find_cli(e->cmda, 1)) {
1095 AST_LIST_UNLOCK(&helpers);
1096 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1097 goto done;
1099 e->_full_cmd = ast_strdup(fulle);
1100 if (!e->_full_cmd)
1101 goto done;
1102 lf = strlen(fulle);
1103 AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1104 int len = strlen(cur->_full_cmd);
1105 if (lf < len)
1106 len = lf;
1107 if (strncasecmp(fulle, cur->_full_cmd, len) < 0) {
1108 AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list);
1109 break;
1112 AST_LIST_TRAVERSE_SAFE_END;
1114 if (!cur)
1115 AST_LIST_INSERT_TAIL(&helpers, e, list);
1116 ret = 0; /* success */
1118 done:
1119 AST_LIST_UNLOCK(&helpers);
1121 return ret;
1125 * register/unregister an array of entries.
1127 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1129 int i;
1131 for (i = 0; i < len; i++)
1132 ast_cli_register(e + i);
1135 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1137 int i;
1139 for (i = 0; i < len; i++)
1140 ast_cli_unregister(e + i);
1144 /*! \brief helper for help_workhorse and final part of
1145 * handle_help. if locked = 0 it's just help_workhorse,
1146 * otherwise assume the list is already locked and print
1147 * an error message if not found.
1149 static int help1(int fd, char *match[], int locked)
1151 char matchstr[80] = "";
1152 struct ast_cli_entry *e;
1153 int len = 0;
1154 int found = 0;
1155 struct cli_iterator i = { NULL, NULL};
1157 if (match) {
1158 ast_join(matchstr, sizeof(matchstr), match);
1159 len = strlen(matchstr);
1161 if (!locked)
1162 AST_LIST_LOCK(&helpers);
1163 while ( (e = cli_next(&i)) ) {
1164 /* Hide commands that start with '_' */
1165 if (e->_full_cmd[0] == '_')
1166 continue;
1167 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1168 continue;
1169 ast_cli(fd, "%25.25s %s\n", e->_full_cmd, e->summary);
1170 found++;
1172 AST_LIST_UNLOCK(&helpers);
1173 if (!locked && !found && matchstr[0])
1174 ast_cli(fd, "No such command '%s'.\n", matchstr);
1175 return 0;
1178 static int help_workhorse(int fd, char *match[])
1180 return help1(fd, match, 0 /* do not print errors */);
1183 static int handle_help(int fd, int argc, char *argv[])
1185 char fullcmd[80];
1186 struct ast_cli_entry *e;
1188 if (argc < 1)
1189 return RESULT_SHOWUSAGE;
1190 if (argc == 1)
1191 return help_workhorse(fd, NULL);
1193 AST_LIST_LOCK(&helpers);
1194 e = find_cli(argv + 1, 1); /* try exact match first */
1195 if (!e)
1196 return help1(fd, argv + 1, 1 /* locked */);
1197 if (e->usage)
1198 ast_cli(fd, "%s", e->usage);
1199 else {
1200 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1201 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1203 AST_LIST_UNLOCK(&helpers);
1204 return RESULT_SUCCESS;
1207 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1209 char *dup, *cur;
1210 int x = 0;
1211 int quoted = 0;
1212 int escaped = 0;
1213 int whitespace = 1;
1215 *trailingwhitespace = 0;
1216 if (s == NULL) /* invalid, though! */
1217 return NULL;
1218 /* make a copy to store the parsed string */
1219 if (!(dup = ast_strdup(s)))
1220 return NULL;
1222 cur = dup;
1223 /* scan the original string copying into cur when needed */
1224 for (; *s ; s++) {
1225 if (x >= max - 1) {
1226 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1227 break;
1229 if (*s == '"' && !escaped) {
1230 quoted = !quoted;
1231 if (quoted && whitespace) {
1232 /* start a quoted string from previous whitespace: new argument */
1233 argv[x++] = cur;
1234 whitespace = 0;
1236 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1237 /* If we are not already in whitespace, and not in a quoted string or
1238 processing an escape sequence, and just entered whitespace, then
1239 finalize the previous argument and remember that we are in whitespace
1241 if (!whitespace) {
1242 *cur++ = '\0';
1243 whitespace = 1;
1245 } else if (*s == '\\' && !escaped) {
1246 escaped = 1;
1247 } else {
1248 if (whitespace) {
1249 /* we leave whitespace, and are not quoted. So it's a new argument */
1250 argv[x++] = cur;
1251 whitespace = 0;
1253 *cur++ = *s;
1254 escaped = 0;
1257 /* Null terminate */
1258 *cur++ = '\0';
1259 /* XXX put a NULL in the last argument, because some functions that take
1260 * the array may want a null-terminated array.
1261 * argc still reflects the number of non-NULL entries.
1263 argv[x] = NULL;
1264 *argc = x;
1265 *trailingwhitespace = whitespace;
1266 return dup;
1269 /*! \brief Return the number of unique matches for the generator */
1270 int ast_cli_generatornummatches(const char *text, const char *word)
1272 int matches = 0, i = 0;
1273 char *buf = NULL, *oldbuf = NULL;
1275 while ((buf = ast_cli_generator(text, word, i++))) {
1276 if (!oldbuf || strcmp(buf,oldbuf))
1277 matches++;
1278 if (oldbuf)
1279 free(oldbuf);
1280 oldbuf = buf;
1282 if (oldbuf)
1283 free(oldbuf);
1284 return matches;
1287 char **ast_cli_completion_matches(const char *text, const char *word)
1289 char **match_list = NULL, *retstr, *prevstr;
1290 size_t match_list_len, max_equal, which, i;
1291 int matches = 0;
1293 /* leave entry 0 free for the longest common substring */
1294 match_list_len = 1;
1295 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1296 if (matches + 1 >= match_list_len) {
1297 match_list_len <<= 1;
1298 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1299 return NULL;
1301 match_list[++matches] = retstr;
1304 if (!match_list)
1305 return match_list; /* NULL */
1307 /* Find the longest substring that is common to all results
1308 * (it is a candidate for completion), and store a copy in entry 0.
1310 prevstr = match_list[1];
1311 max_equal = strlen(prevstr);
1312 for (which = 2; which <= matches; which++) {
1313 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1314 continue;
1315 max_equal = i;
1318 if (!(retstr = ast_malloc(max_equal + 1)))
1319 return NULL;
1321 strncpy(retstr, match_list[1], max_equal);
1322 retstr[max_equal] = '\0';
1323 match_list[0] = retstr;
1325 /* ensure that the array is NULL terminated */
1326 if (matches + 1 >= match_list_len) {
1327 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1328 return NULL;
1330 match_list[matches + 1] = NULL;
1332 return match_list;
1335 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1337 char *argv[AST_MAX_ARGS];
1338 struct ast_cli_entry *e;
1339 struct cli_iterator i = { NULL, NULL };
1340 int x = 0, argindex, matchlen;
1341 int matchnum=0;
1342 char *ret = NULL;
1343 char matchstr[80] = "";
1344 int tws = 0;
1345 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1347 if (!dup) /* error */
1348 return NULL;
1349 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1350 /* rebuild the command, ignore tws */
1351 ast_join(matchstr, sizeof(matchstr)-1, argv);
1352 matchlen = strlen(matchstr);
1353 if (tws) {
1354 strcat(matchstr, " "); /* XXX */
1355 if (matchlen)
1356 matchlen++;
1358 if (lock)
1359 AST_LIST_LOCK(&helpers);
1360 while( !ret && (e = cli_next(&i)) ) {
1361 int lc = strlen(e->_full_cmd);
1362 if (e->_full_cmd[0] != '_' && lc > 0 && matchlen <= lc &&
1363 !strncasecmp(matchstr, e->_full_cmd, matchlen)) {
1364 /* Found initial part, return a copy of the next word... */
1365 if (e->cmda[argindex] && ++matchnum > state)
1366 ret = strdup(e->cmda[argindex]); /* we need a malloced string */
1367 } else if (e->generator && !strncasecmp(matchstr, e->_full_cmd, lc) && matchstr[lc] < 33) {
1368 /* We have a command in its entirity within us -- theoretically only one
1369 command can have this occur */
1370 ret = e->generator(matchstr, word, argindex, state);
1373 if (lock)
1374 AST_LIST_UNLOCK(&helpers);
1375 free(dup);
1376 return ret;
1379 char *ast_cli_generator(const char *text, const char *word, int state)
1381 return __ast_cli_generator(text, word, state, 1);
1384 int ast_cli_command(int fd, const char *s)
1386 char *argv[AST_MAX_ARGS];
1387 struct ast_cli_entry *e;
1388 int x;
1389 char *dup;
1390 int tws;
1392 if (!(dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws)))
1393 return -1;
1395 /* We need at least one entry, or ignore */
1396 if (x > 0) {
1397 AST_LIST_LOCK(&helpers);
1398 e = find_cli(argv, 0);
1399 if (e)
1400 e->inuse++;
1401 AST_LIST_UNLOCK(&helpers);
1402 if (e) {
1403 switch(e->handler(fd, x, argv)) {
1404 case RESULT_SHOWUSAGE:
1405 if (e->usage)
1406 ast_cli(fd, "%s", e->usage);
1407 else
1408 ast_cli(fd, "Invalid usage, but no usage information available.\n");
1409 break;
1411 } else
1412 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1413 if (e)
1414 ast_atomic_fetchadd_int(&e->inuse, -1);
1416 free(dup);
1418 return 0;