officially deprecate the 'roundrobin' queue strategy in favor of 'rrmemory'
[asterisk-bristuff.git] / cli.c
blob126f16b72b191732d3ffe7a357dea692884f3956
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 <unistd.h>
27 #include <stdlib.h>
28 #include <sys/signal.h>
29 #include <stdio.h>
30 #include <signal.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <regex.h>
35 #include "asterisk.h"
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39 #include "asterisk/logger.h"
40 #include "asterisk/options.h"
41 #include "asterisk/cli.h"
42 #include "asterisk/linkedlists.h"
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 /* For rl_filename_completion */
51 #include "editline/readline/readline.h"
52 /* For module directory */
54 extern unsigned long global_fin, global_fout;
56 void ast_cli(int fd, char *fmt, ...)
58 char *stuff;
59 int res;
60 va_list ap;
62 va_start(ap, fmt);
63 res = vasprintf(&stuff, fmt, ap);
64 va_end(ap);
65 if (res == -1) {
66 ast_log(LOG_ERROR, "Memory allocation failure\n");
67 } else {
68 ast_carefulwrite(fd, stuff, strlen(stuff), 100);
69 free(stuff);
73 static AST_LIST_HEAD_STATIC(helpers, ast_cli_entry);
75 static char load_help[] =
76 "Usage: load <module name>\n"
77 " Loads the specified module into Asterisk.\n";
79 static char unload_help[] =
80 "Usage: unload [-f|-h] <module name>\n"
81 " Unloads the specified module from Asterisk. The -f\n"
82 " option causes the module to be unloaded even if it is\n"
83 " in use (may cause a crash) and the -h module causes the\n"
84 " module to be unloaded even if the module says it cannot, \n"
85 " which almost always will cause a crash.\n";
87 static char help_help[] =
88 "Usage: help [topic]\n"
89 " When called with a topic as an argument, displays usage\n"
90 " information on the given command. If called without a\n"
91 " topic, it provides a list of commands.\n";
93 static char chanlist_help[] =
94 "Usage: show channels [concise|verbose]\n"
95 " Lists currently defined channels and some information about them. If\n"
96 " 'concise' is specified, the format is abridged and in a more easily\n"
97 " machine parsable format. If 'verbose' is specified, the output includes\n"
98 " more and longer fields.\n";
100 static char reload_help[] =
101 "Usage: reload [module ...]\n"
102 " Reloads configuration files for all listed modules which support\n"
103 " reloading, or for all supported modules if none are listed.\n";
105 static char set_verbose_help[] =
106 "Usage: set verbose <level>\n"
107 " Sets level of verbose messages to be displayed. 0 means\n"
108 " no messages should be displayed. Equivalent to -v[v[v...]]\n"
109 " on startup\n";
111 static char set_debug_help[] =
112 "Usage: set debug <level>\n"
113 " Sets level of core debug messages to be displayed. 0 means\n"
114 " no messages should be displayed. Equivalent to -d[d[d...]]\n"
115 " on startup.\n";
117 static char logger_mute_help[] =
118 "Usage: logger mute\n"
119 " Disables logging output to the current console, making it possible to\n"
120 " gather information without being disturbed by scrolling lines.\n";
122 static char softhangup_help[] =
123 "Usage: soft hangup <channel>\n"
124 " Request that a channel be hung up. The hangup takes effect\n"
125 " the next time the driver reads or writes from the channel\n";
127 static char group_show_channels_help[] =
128 "Usage: group show channels [pattern]\n"
129 " Lists all currently active channels with channel group(s) specified.\n"
130 " Optional regular expression pattern is matched to group names for each\n"
131 " channel.\n";
133 static char frog_help[] =
134 "Usage: frog [warp_factor]\n"
135 " Performs frog-in-a-blender calculations (Jacobsen Corollary)\n";
137 static int handle_load(int fd, int argc, char *argv[])
139 if (argc != 2)
140 return RESULT_SHOWUSAGE;
141 if (ast_load_resource(argv[1])) {
142 ast_cli(fd, "Unable to load module %s\n", argv[1]);
143 return RESULT_FAILURE;
145 return RESULT_SUCCESS;
148 static int handle_reload(int fd, int argc, char *argv[])
150 int x;
151 int res;
152 if (argc < 1)
153 return RESULT_SHOWUSAGE;
154 if (argc > 1) {
155 for (x=1;x<argc;x++) {
156 res = ast_module_reload(argv[x]);
157 switch(res) {
158 case 0:
159 ast_cli(fd, "No such module '%s'\n", argv[x]);
160 break;
161 case 1:
162 ast_cli(fd, "Module '%s' does not support reload\n", argv[x]);
163 break;
166 } else
167 ast_module_reload(NULL);
168 return RESULT_SUCCESS;
171 static int handle_set_verbose(int fd, int argc, char *argv[])
173 int val = 0;
174 int oldval = option_verbose;
176 /* "set verbose [atleast] N" */
177 if (argc == 3)
178 option_verbose = atoi(argv[2]);
179 else if (argc == 4) {
180 if (strcasecmp(argv[2], "atleast"))
181 return RESULT_SHOWUSAGE;
182 val = atoi(argv[3]);
183 if (val > option_verbose)
184 option_verbose = val;
185 } else
186 return RESULT_SHOWUSAGE;
187 if (oldval != option_verbose && option_verbose > 0)
188 ast_cli(fd, "Verbosity was %d and is now %d\n", oldval, option_verbose);
189 else if (oldval > 0 && option_verbose > 0)
190 ast_cli(fd, "Verbosity is at least %d\n", option_verbose);
191 else if (oldval > 0 && option_verbose == 0)
192 ast_cli(fd, "Verbosity is now OFF\n");
193 return RESULT_SUCCESS;
196 static int handle_set_debug(int fd, int argc, char *argv[])
198 int val = 0;
199 int oldval = option_debug;
201 /* "set debug [atleast] N" */
202 if (argc == 3)
203 option_debug = atoi(argv[2]);
204 else if (argc == 4) {
205 if (strcasecmp(argv[2], "atleast"))
206 return RESULT_SHOWUSAGE;
207 val = atoi(argv[3]);
208 if (val > option_debug)
209 option_debug = val;
210 } else
211 return RESULT_SHOWUSAGE;
212 if (oldval != option_debug && option_debug > 0)
213 ast_cli(fd, "Core debug was %d and is now %d\n", oldval, option_debug);
214 else if (oldval > 0 && option_debug > 0)
215 ast_cli(fd, "Core debug is at least %d\n", option_debug);
216 else if (oldval > 0 && option_debug == 0)
217 ast_cli(fd, "Core debug is now OFF\n");
218 return RESULT_SUCCESS;
221 static int handle_logger_mute(int fd, int argc, char *argv[])
223 if (argc != 2)
224 return RESULT_SHOWUSAGE;
225 ast_console_toggle_mute(fd);
226 return RESULT_SUCCESS;
229 static int handle_unload(int fd, int argc, char *argv[])
231 int x;
232 int force=AST_FORCE_SOFT;
233 if (argc < 2)
234 return RESULT_SHOWUSAGE;
235 for (x=1;x<argc;x++) {
236 if (argv[x][0] == '-') {
237 switch(argv[x][1]) {
238 case 'f':
239 force = AST_FORCE_FIRM;
240 break;
241 case 'h':
242 force = AST_FORCE_HARD;
243 break;
244 default:
245 return RESULT_SHOWUSAGE;
247 } else if (x != argc - 1)
248 return RESULT_SHOWUSAGE;
249 else if (ast_unload_resource(argv[x], force)) {
250 ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
251 return RESULT_FAILURE;
254 return RESULT_SUCCESS;
258 * Perform frong-in-a-blender calculations (Jacobsen Corollary)
261 static int handle_frog(int fd, int argc, char *argv[])
263 double warpone = 75139293848.0;
264 double warpfactor = 1.0;
266 if (argc > 2)
267 return RESULT_SHOWUSAGE;
268 if (argc > 1 && sscanf(argv[1], "%lf", &warpfactor) != 1)
269 return RESULT_SHOWUSAGE;
271 ast_cli(fd, "A frog in a blender with a base diameter of 3 inches going\n");
272 ast_cli(fd, "%.0f RPM will be travelling at warp factor %f,\n",
273 warpfactor * warpfactor * warpfactor * warpone, warpfactor);
274 ast_cli(fd, "based upon the Jacobsen Frog Corollary.\n");
275 return RESULT_SUCCESS;
279 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
280 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
282 AST_MUTEX_DEFINE_STATIC(climodentrylock);
283 static int climodentryfd = -1;
285 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
287 /* Comparing the like with the module */
288 if (strcasestr(module, like) ) {
289 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
290 return 1;
292 return 0;
295 static char modlist_help[] =
296 "Usage: show modules [like keyword]\n"
297 " Shows Asterisk modules currently in use, and usage statistics.\n";
299 static char uptime_help[] =
300 "Usage: show uptime [seconds]\n"
301 " Shows Asterisk uptime information.\n"
302 " The seconds word returns the uptime in seconds only.\n";
304 static void print_uptimestr(int fd, time_t timeval, const char *prefix, int printsec)
306 int x; /* the main part - years, weeks, etc. */
307 char timestr[256]="", *s = timestr;
308 size_t maxbytes = sizeof(timestr);
310 #define SECOND (1)
311 #define MINUTE (SECOND*60)
312 #define HOUR (MINUTE*60)
313 #define DAY (HOUR*24)
314 #define WEEK (DAY*7)
315 #define YEAR (DAY*365)
316 #define ESS(x) ((x == 1) ? "" : "s") /* plural suffix */
317 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
318 if (timeval < 0) /* invalid, nothing to show */
319 return;
320 if (printsec) { /* plain seconds output */
321 ast_build_string(&s, &maxbytes, "%lu", (u_long)timeval);
322 timeval = 0; /* bypass the other cases */
324 if (timeval > YEAR) {
325 x = (timeval / YEAR);
326 timeval -= (x * YEAR);
327 ast_build_string(&s, &maxbytes, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval));
329 if (timeval > WEEK) {
330 x = (timeval / WEEK);
331 timeval -= (x * WEEK);
332 ast_build_string(&s, &maxbytes, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval));
334 if (timeval > DAY) {
335 x = (timeval / DAY);
336 timeval -= (x * DAY);
337 ast_build_string(&s, &maxbytes, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval));
339 if (timeval > HOUR) {
340 x = (timeval / HOUR);
341 timeval -= (x * HOUR);
342 ast_build_string(&s, &maxbytes, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval));
344 if (timeval > MINUTE) {
345 x = (timeval / MINUTE);
346 timeval -= (x * MINUTE);
347 ast_build_string(&s, &maxbytes, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval));
349 x = timeval;
350 if (x > 0)
351 ast_build_string(&s, &maxbytes, "%d second%s ", x, ESS(x));
352 if (timestr[0] != '\0')
353 ast_cli(fd, "%s: %s\n", prefix, timestr);
356 static int handle_showuptime(int fd, int argc, char *argv[])
358 /* 'show uptime [seconds]' */
359 time_t curtime = time(NULL);
360 int printsec = (argc == 3 && !strcasecmp(argv[2],"seconds"));
362 if (argc != 2 && !printsec)
363 return RESULT_SHOWUSAGE;
364 if (ast_startuptime)
365 print_uptimestr(fd, curtime - ast_startuptime, "System uptime", printsec);
366 if (ast_lastreloadtime)
367 print_uptimestr(fd, curtime - ast_lastreloadtime, "Last reload", printsec);
368 return RESULT_SUCCESS;
371 static int handle_modlist(int fd, int argc, char *argv[])
373 char *like = "";
374 if (argc == 3)
375 return RESULT_SHOWUSAGE;
376 else if (argc >= 4) {
377 if (strcmp(argv[2],"like"))
378 return RESULT_SHOWUSAGE;
379 like = argv[3];
382 ast_mutex_lock(&climodentrylock);
383 climodentryfd = fd; /* global, protected by climodentrylock */
384 ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
385 ast_cli(fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
386 climodentryfd = -1;
387 ast_mutex_unlock(&climodentrylock);
388 return RESULT_SUCCESS;
390 #undef MODLIST_FORMAT
391 #undef MODLIST_FORMAT2
393 static int handle_chanlist(int fd, int argc, char *argv[])
395 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
396 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
397 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s\n"
398 #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"
399 #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"
401 struct ast_channel *c = NULL;
402 char durbuf[10] = "-";
403 char locbuf[40];
404 char appdata[40];
405 int duration;
406 int durh, durm, durs;
407 int numchans = 0, concise = 0, verbose = 0;
409 concise = (argc == 3 && (!strcasecmp(argv[2],"concise")));
410 verbose = (argc == 3 && (!strcasecmp(argv[2],"verbose")));
412 if (argc < 2 || argc > 3 || (argc == 3 && !concise && !verbose))
413 return RESULT_SHOWUSAGE;
415 if (!concise && !verbose)
416 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
417 else if (verbose)
418 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
419 "CallerID", "Duration", "Accountcode", "BridgedTo");
421 while ((c = ast_channel_walk_locked(c)) != NULL) {
422 struct ast_channel *bc = ast_bridged_channel(c);
423 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
424 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
425 if (verbose) {
426 durh = duration / 3600;
427 durm = (duration % 3600) / 60;
428 durs = duration % 60;
429 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
430 } else {
431 snprintf(durbuf, sizeof(durbuf), "%d", duration);
433 } else {
434 durbuf[0] = '\0';
436 if (concise) {
437 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
438 c->appl ? c->appl : "(None)",
439 S_OR(c->data, ""), /* XXX different from verbose ? */
440 S_OR(c->cid.cid_num, ""),
441 S_OR(c->accountcode, ""),
442 c->amaflags,
443 durbuf,
444 bc ? bc->name : "(None)");
445 } else if (verbose) {
446 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
447 c->appl ? c->appl : "(None)",
448 c->data ? S_OR(c->data, "(Empty)" ): "(None)",
449 S_OR(c->cid.cid_num, ""),
450 durbuf,
451 S_OR(c->accountcode, ""),
452 bc ? bc->name : "(None)");
453 } else {
454 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
455 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
456 else
457 strcpy(locbuf, "(None)");
458 if (c->appl)
459 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, c->data ? c->data : "");
460 else
461 strcpy(appdata, "(None)");
462 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
464 numchans++;
465 ast_channel_unlock(c);
467 if (!concise) {
468 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
469 if (option_maxcalls)
470 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
471 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
472 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
473 else
474 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
476 return RESULT_SUCCESS;
478 #undef FORMAT_STRING
479 #undef FORMAT_STRING2
480 #undef CONCISE_FORMAT_STRING
481 #undef VERBOSE_FORMAT_STRING
482 #undef VERBOSE_FORMAT_STRING2
485 static char showchan_help[] =
486 "Usage: show channel <channel>\n"
487 " Shows lots of information about the specified channel.\n";
489 static char debugchan_help[] =
490 "Usage: debug channel <channel>\n"
491 " Enables debugging on a specific channel.\n";
493 static char debuglevel_help[] =
494 "Usage: debug level <level> [filename]\n"
495 " Set debug to specified level (0 to disable). If filename\n"
496 "is specified, debugging will be limited to just that file.\n";
498 static char nodebugchan_help[] =
499 "Usage: no debug channel <channel>\n"
500 " Disables debugging on a specific channel.\n";
502 static char commandcomplete_help[] =
503 "Usage: _command complete \"<line>\" text state\n"
504 " This function is used internally to help with command completion and should.\n"
505 " never be called by the user directly.\n";
507 static char commandnummatches_help[] =
508 "Usage: _command nummatches \"<line>\" text \n"
509 " This function is used internally to help with command completion and should.\n"
510 " never be called by the user directly.\n";
512 static char commandmatchesarray_help[] =
513 "Usage: _command matchesarray \"<line>\" text \n"
514 " This function is used internally to help with command completion and should.\n"
515 " never be called by the user directly.\n";
517 static int handle_softhangup(int fd, int argc, char *argv[])
519 struct ast_channel *c=NULL;
520 if (argc != 3)
521 return RESULT_SHOWUSAGE;
522 c = ast_get_channel_by_name_locked(argv[2]);
523 if (c) {
524 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
525 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
526 ast_channel_unlock(c);
527 } else
528 ast_cli(fd, "%s is not a known channel\n", argv[2]);
529 return RESULT_SUCCESS;
532 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
534 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
536 char *buf, *obuf;
537 int buflen = 2048;
538 int len = 0;
539 char **matches;
540 int x, matchlen;
542 if (argc != 4)
543 return RESULT_SHOWUSAGE;
544 if (!(buf = ast_malloc(buflen)))
545 return RESULT_FAILURE;
546 buf[len] = '\0';
547 matches = ast_cli_completion_matches(argv[2], argv[3]);
548 if (matches) {
549 for (x=0; matches[x]; x++) {
550 matchlen = strlen(matches[x]) + 1;
551 if (len + matchlen >= buflen) {
552 buflen += matchlen * 3;
553 obuf = buf;
554 if (!(buf = ast_realloc(obuf, buflen)))
555 /* Memory allocation failure... Just free old buffer and be done */
556 free(obuf);
558 if (buf)
559 len += sprintf( buf + len, "%s ", matches[x]);
560 free(matches[x]);
561 matches[x] = NULL;
563 free(matches);
566 if (buf) {
567 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
568 free(buf);
569 } else
570 ast_cli(fd, "NULL\n");
572 return RESULT_SUCCESS;
577 static int handle_commandnummatches(int fd, int argc, char *argv[])
579 int matches = 0;
581 if (argc != 4)
582 return RESULT_SHOWUSAGE;
584 matches = ast_cli_generatornummatches(argv[2], argv[3]);
586 ast_cli(fd, "%d", matches);
588 return RESULT_SUCCESS;
591 static int handle_commandcomplete(int fd, int argc, char *argv[])
593 char *buf;
595 if (argc != 5)
596 return RESULT_SHOWUSAGE;
597 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
598 if (buf) {
599 ast_cli(fd, buf);
600 free(buf);
601 } else
602 ast_cli(fd, "NULL\n");
603 return RESULT_SUCCESS;
606 static int handle_debuglevel(int fd, int argc, char *argv[])
608 int newlevel;
609 char *filename = "<any>";
610 if ((argc < 3) || (argc > 4))
611 return RESULT_SHOWUSAGE;
612 if (sscanf(argv[2], "%d", &newlevel) != 1)
613 return RESULT_SHOWUSAGE;
614 option_debug = newlevel;
615 if (argc == 4) {
616 filename = argv[3];
617 ast_copy_string(debug_filename, filename, sizeof(debug_filename));
618 } else {
619 debug_filename[0] = '\0';
621 ast_cli(fd, "Debugging level set to %d, file '%s'\n", newlevel, filename);
622 return RESULT_SUCCESS;
625 /* XXX todo: merge next two functions!!! */
626 static int handle_debugchan(int fd, int argc, char *argv[])
628 struct ast_channel *c=NULL;
629 int is_all;
631 /* 'debug channel {all|chan_id}' */
632 if (argc != 3)
633 return RESULT_SHOWUSAGE;
635 is_all = !strcasecmp("all", argv[2]);
636 if (is_all) {
637 global_fin |= DEBUGCHAN_FLAG;
638 global_fout |= DEBUGCHAN_FLAG;
639 c = ast_channel_walk_locked(NULL);
640 } else {
641 c = ast_get_channel_by_name_locked(argv[2]);
642 if (c == NULL)
643 ast_cli(fd, "No such channel %s\n", argv[2]);
645 while (c) {
646 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
647 c->fin |= DEBUGCHAN_FLAG;
648 c->fout |= DEBUGCHAN_FLAG;
649 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
651 ast_channel_unlock(c);
652 if (!is_all)
653 break;
654 c = ast_channel_walk_locked(c);
656 ast_cli(fd, "Debugging on new channels is enabled\n");
657 return RESULT_SUCCESS;
660 static int handle_nodebugchan(int fd, int argc, char *argv[])
662 struct ast_channel *c=NULL;
663 int is_all;
664 /* 'no debug channel {all|chan_id}' */
665 if (argc != 4)
666 return RESULT_SHOWUSAGE;
667 is_all = !strcasecmp("all", argv[3]);
668 if (is_all) {
669 global_fin &= ~DEBUGCHAN_FLAG;
670 global_fout &= ~DEBUGCHAN_FLAG;
671 c = ast_channel_walk_locked(NULL);
672 } else {
673 c = ast_get_channel_by_name_locked(argv[3]);
674 if (c == NULL)
675 ast_cli(fd, "No such channel %s\n", argv[3]);
677 while(c) {
678 if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
679 c->fin &= ~DEBUGCHAN_FLAG;
680 c->fout &= ~DEBUGCHAN_FLAG;
681 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
683 ast_channel_unlock(c);
684 if (!is_all)
685 break;
686 c = ast_channel_walk_locked(c);
688 ast_cli(fd, "Debugging on new channels is disabled\n");
689 return RESULT_SUCCESS;
692 static int handle_showchan(int fd, int argc, char *argv[])
694 struct ast_channel *c=NULL;
695 struct timeval now;
696 char buf[2048];
697 char cdrtime[256];
698 char nf[256], wf[256], rf[256];
699 long elapsed_seconds=0;
700 int hour=0, min=0, sec=0;
702 if (argc != 3)
703 return RESULT_SHOWUSAGE;
704 now = ast_tvnow();
705 c = ast_get_channel_by_name_locked(argv[2]);
706 if (!c) {
707 ast_cli(fd, "%s is not a known channel\n", argv[2]);
708 return RESULT_SUCCESS;
710 if(c->cdr) {
711 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
712 hour = elapsed_seconds / 3600;
713 min = (elapsed_seconds % 3600) / 60;
714 sec = elapsed_seconds % 60;
715 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
716 } else
717 strcpy(cdrtime, "N/A");
718 ast_cli(fd,
719 " -- General --\n"
720 " Name: %s\n"
721 " Type: %s\n"
722 " UniqueID: %s\n"
723 " Caller ID: %s\n"
724 " Caller ID Name: %s\n"
725 " DNID Digits: %s\n"
726 " State: %s (%d)\n"
727 " Rings: %d\n"
728 " NativeFormats: %s\n"
729 " WriteFormat: %s\n"
730 " ReadFormat: %s\n"
731 "1st File Descriptor: %d\n"
732 " Frames in: %d%s\n"
733 " Frames out: %d%s\n"
734 " Time to Hangup: %ld\n"
735 " Elapsed Time: %s\n"
736 " Direct Bridge: %s\n"
737 "Indirect Bridge: %s\n"
738 " -- PBX --\n"
739 " Context: %s\n"
740 " Extension: %s\n"
741 " Priority: %d\n"
742 " Call Group: %d\n"
743 " Pickup Group: %d\n"
744 " Application: %s\n"
745 " Data: %s\n"
746 " Blocking in: %s\n",
747 c->name, c->tech->type, c->uniqueid,
748 S_OR(c->cid.cid_num, "(N/A)"),
749 S_OR(c->cid.cid_name, "(N/A)"),
750 S_OR(c->cid.cid_dnid, "(N/A)"), ast_state2str(c->_state), c->_state, c->rings,
751 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
752 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
753 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
754 c->fds[0],
755 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
756 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
757 (long)c->whentohangup,
758 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
759 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
760 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
761 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
763 if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
764 ast_cli(fd," Variables:\n%s\n",buf);
765 if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
766 ast_cli(fd," CDR Variables:\n%s\n",buf);
768 ast_channel_unlock(c);
769 return RESULT_SUCCESS;
773 * helper function to generate CLI matches from a fixed set of values.
774 * A NULL word is acceptable.
776 char *ast_cli_complete(const char *word, char *const choices[], int state)
778 int i, which = 0, len;
779 len = ast_strlen_zero(word) ? 0 : strlen(word);
781 for (i = 0; choices[i]; i++) {
782 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
783 return ast_strdup(choices[i]);
785 return NULL;
788 static char *complete_show_channels(const char *line, const char *word, int pos, int state)
790 static char *choices[] = { "concise", "verbose", NULL };
792 return (pos != 2) ? NULL : ast_cli_complete(word, choices, state);
795 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
797 struct ast_channel *c = NULL;
798 int which = 0;
799 int wordlen;
800 char notfound = '\0';
801 char *ret = &notfound; /* so NULL can break the loop */
803 if (pos != rpos)
804 return NULL;
806 wordlen = strlen(word);
808 while (ret == &notfound && (c = ast_channel_walk_locked(c))) {
809 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
810 ret = ast_strdup(c->name);
811 ast_channel_unlock(c);
813 return ret == &notfound ? NULL : ret;
816 static char *complete_ch_3(const char *line, const char *word, int pos, int state)
818 return ast_complete_channels(line, word, pos, state, 2);
821 static char *complete_ch_4(const char *line, const char *word, int pos, int state)
823 return ast_complete_channels(line, word, pos, state, 3);
826 static char *complete_mod_2(const char *line, const char *word, int pos, int state)
828 return ast_module_helper(line, word, pos, state, 1, 1);
831 static char *complete_mod_4(const char *line, const char *word, int pos, int state)
833 return ast_module_helper(line, word, pos, state, 3, 0);
836 static char *complete_fn(const char *line, const char *word, int pos, int state)
838 char *c;
839 char filename[256];
841 if (pos != 1)
842 return NULL;
844 if (word[0] == '/')
845 ast_copy_string(filename, word, sizeof(filename));
846 else
847 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
849 c = filename_completion_function(filename, state);
851 if (c && word[0] != '/')
852 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
854 return c ? strdup(c) : c;
857 static int group_show_channels(int fd, int argc, char *argv[])
859 #define FORMAT_STRING "%-25s %-20s %-20s\n"
861 struct ast_channel *c = NULL;
862 int numchans = 0;
863 struct ast_var_t *current;
864 struct varshead *headp;
865 regex_t regexbuf;
866 int havepattern = 0;
868 if (argc < 3 || argc > 4)
869 return RESULT_SHOWUSAGE;
871 if (argc == 4) {
872 if (regcomp(&regexbuf, argv[3], REG_EXTENDED | REG_NOSUB))
873 return RESULT_SHOWUSAGE;
874 havepattern = 1;
877 ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
878 while ( (c = ast_channel_walk_locked(c)) != NULL) {
879 headp=&c->varshead;
880 AST_LIST_TRAVERSE(headp,current,entries) {
881 if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
882 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
883 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
884 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
885 numchans++;
887 } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
888 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
889 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
890 numchans++;
894 numchans++;
895 ast_channel_unlock(c);
898 if (havepattern)
899 regfree(&regexbuf);
901 ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
902 return RESULT_SUCCESS;
903 #undef FORMAT_STRING
906 static int handle_help(int fd, int argc, char *argv[]);
908 static char * complete_help(const char *text, const char *word, int pos, int state)
910 /* skip first 4 or 5 chars, "help "*/
911 int l = strlen(text);
913 if (l > 5)
914 l = 5;
915 text += l;
916 /* XXX watch out, should stop to the non-generator parts */
917 return __ast_cli_generator(text, word, state, 0);
920 static struct ast_cli_entry builtins[] = {
921 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
922 { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
923 { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
924 { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
925 { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch_3 },
926 { { "debug", "level", NULL }, handle_debuglevel, "Set global debug level", debuglevel_help },
927 { { "frog", NULL }, handle_frog,"Perform frog-in-a-blender calculations", frog_help },
928 { { "group", "show", "channels", NULL }, group_show_channels, "Show active channels with group(s)", group_show_channels_help},
929 { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help, complete_help },
930 { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
931 { { "logger", "mute", NULL }, handle_logger_mute, "Toggle logging output to a console", logger_mute_help },
932 { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch_4 },
933 { { "reload", NULL }, handle_reload, "Reload configuration", reload_help, complete_mod_2 },
934 { { "set", "debug", NULL }, handle_set_debug, "Set level of debug chattiness", set_debug_help },
935 { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
936 { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch_3 },
937 { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help, complete_show_channels },
938 { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
939 { { "show", "modules", "like", NULL }, handle_modlist, "List modules and info", modlist_help, complete_mod_4 },
940 { { "show", "uptime", NULL }, handle_showuptime, "Show uptime information", uptime_help },
941 { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch_3 },
942 { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
943 { { NULL }, NULL, NULL, NULL }
946 /*! \brief initialize the _full_cmd string in * each of the builtins. */
947 void ast_builtins_init(void)
949 struct ast_cli_entry *e;
951 for (e = builtins; e->cmda[0] != NULL; e++) {
952 char buf[80];
953 ast_join(buf, sizeof(buf), e->cmda);
954 e->_full_cmd = strdup(buf);
955 if (!e->_full_cmd)
956 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
961 * We have two sets of commands: builtins are stored in a
962 * NULL-terminated array of ast_cli_entry, whereas external
963 * commands are in a list.
964 * When navigating, we need to keep two pointers and get
965 * the next one in lexicographic order. For the purpose,
966 * we use a structure.
969 struct cli_iterator {
970 struct ast_cli_entry *builtins;
971 struct ast_cli_entry *helpers;
974 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
976 struct ast_cli_entry *e;
978 if (i->builtins == NULL && i->helpers == NULL) {
979 /* initialize */
980 i->builtins = builtins;
981 i->helpers = AST_LIST_FIRST(&helpers);
983 e = i->builtins; /* temporary */
984 if (!e->cmda[0] || (i->helpers &&
985 strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
986 /* Use helpers */
987 e = i->helpers;
988 if (e)
989 i->helpers = AST_LIST_NEXT(e, list);
990 } else { /* use builtin. e is already set */
991 (i->builtins)++; /* move to next */
993 return e;
997 * \brief locate a cli command in the 'helpers' list (which must be locked).
998 * exact has 3 values:
999 * 0 returns if the search key is equal or longer than the entry.
1000 * -1 true if the mismatch is on the last word XXX not true!
1001 * 1 true only on complete, exact match.
1003 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1005 int matchlen = -1; /* length of longest match so far */
1006 struct ast_cli_entry *cand = NULL, *e=NULL;
1007 struct cli_iterator i = { NULL, NULL};
1009 while( (e = cli_next(&i)) ) {
1010 int y;
1011 for (y = 0 ; cmds[y] && e->cmda[y]; y++) {
1012 if (strcasecmp(e->cmda[y], cmds[y]))
1013 break;
1015 if (e->cmda[y] == NULL) { /* no more words in candidate */
1016 if (cmds[y] == NULL) /* this is an exact match, cannot do better */
1017 break;
1018 /* here the search key is longer than the candidate */
1019 if (match_type != 0) /* but we look for almost exact match... */
1020 continue; /* so we skip this one. */
1021 /* otherwise we like it (case 0) */
1022 } else { /* still words in candidate */
1023 if (cmds[y] == NULL) /* search key is shorter, not good */
1024 continue;
1025 /* if we get here, both words exist but there is a mismatch */
1026 if (match_type == 0) /* not the one we look for */
1027 continue;
1028 if (match_type == 1) /* not the one we look for */
1029 continue;
1030 if (cmds[y+1] != NULL || e->cmda[y+1] != NULL) /* not the one we look for */
1031 continue;
1032 /* we are in case match_type == -1 and mismatch on last word */
1034 if (cand == NULL || y > matchlen) /* remember the candidate */
1035 cand = e;
1037 return e ? e : cand;
1040 static char *find_best(char *argv[])
1042 static char cmdline[80];
1043 int x;
1044 /* See how close we get, then print the candidate */
1045 char *myargv[AST_MAX_CMD_LEN];
1046 for (x=0;x<AST_MAX_CMD_LEN;x++)
1047 myargv[x]=NULL;
1048 AST_LIST_LOCK(&helpers);
1049 for (x=0;argv[x];x++) {
1050 myargv[x] = argv[x];
1051 if (!find_cli(myargv, -1))
1052 break;
1054 AST_LIST_UNLOCK(&helpers);
1055 ast_join(cmdline, sizeof(cmdline), myargv);
1056 return cmdline;
1059 int ast_cli_unregister(struct ast_cli_entry *e)
1061 if (e->inuse) {
1062 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1063 } else {
1064 AST_LIST_LOCK(&helpers);
1065 AST_LIST_REMOVE(&helpers, e, list);
1066 AST_LIST_UNLOCK(&helpers);
1068 return 0;
1071 int ast_cli_register(struct ast_cli_entry *e)
1073 struct ast_cli_entry *cur;
1074 char fulle[80] ="";
1075 int lf, ret = -1;
1077 ast_join(fulle, sizeof(fulle), e->cmda);
1078 AST_LIST_LOCK(&helpers);
1080 if (find_cli(e->cmda, 1)) {
1081 AST_LIST_UNLOCK(&helpers);
1082 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1083 goto done;
1085 e->_full_cmd = ast_strdup(fulle);
1086 if (!e->_full_cmd)
1087 goto done;
1088 lf = strlen(fulle);
1089 AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1090 int len = strlen(cur->_full_cmd);
1091 if (lf < len)
1092 len = lf;
1093 if (strncasecmp(fulle, cur->_full_cmd, len) < 0) {
1094 AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list);
1095 break;
1098 AST_LIST_TRAVERSE_SAFE_END;
1100 if (!cur)
1101 AST_LIST_INSERT_TAIL(&helpers, e, list);
1102 ret = 0; /* success */
1104 done:
1105 AST_LIST_UNLOCK(&helpers);
1107 return ret;
1111 * register/unregister an array of entries.
1113 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1115 int i;
1117 for (i = 0; i < len; i++)
1118 ast_cli_register(e + i);
1121 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1123 int i;
1125 for (i = 0; i < len; i++)
1126 ast_cli_unregister(e + i);
1130 /*! \brief helper for help_workhorse and final part of
1131 * handle_help. if locked = 0 it's just help_workhorse,
1132 * otherwise assume the list is already locked and print
1133 * an error message if not found.
1135 static int help1(int fd, char *match[], int locked)
1137 char matchstr[80] = "";
1138 struct ast_cli_entry *e;
1139 int len = 0;
1140 int found = 0;
1141 struct cli_iterator i = { NULL, NULL};
1143 if (match) {
1144 ast_join(matchstr, sizeof(matchstr), match);
1145 len = strlen(matchstr);
1147 if (!locked)
1148 AST_LIST_LOCK(&helpers);
1149 while ( (e = cli_next(&i)) ) {
1150 /* Hide commands that start with '_' */
1151 if (e->_full_cmd[0] == '_')
1152 continue;
1153 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1154 continue;
1155 ast_cli(fd, "%25.25s %s\n", e->_full_cmd, e->summary);
1156 found++;
1158 AST_LIST_UNLOCK(&helpers);
1159 if (!locked && !found && matchstr[0])
1160 ast_cli(fd, "No such command '%s'.\n", matchstr);
1161 return 0;
1164 static int help_workhorse(int fd, char *match[])
1166 return help1(fd, match, 0 /* do not print errors */);
1169 static int handle_help(int fd, int argc, char *argv[])
1171 char fullcmd[80];
1172 struct ast_cli_entry *e;
1174 if (argc < 1)
1175 return RESULT_SHOWUSAGE;
1176 if (argc == 1)
1177 return help_workhorse(fd, NULL);
1179 AST_LIST_LOCK(&helpers);
1180 e = find_cli(argv + 1, 1); /* try exact match first */
1181 if (!e)
1182 return help1(fd, argv + 1, 1 /* locked */);
1183 if (e->usage)
1184 ast_cli(fd, "%s", e->usage);
1185 else {
1186 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1187 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1189 AST_LIST_UNLOCK(&helpers);
1190 return RESULT_SUCCESS;
1193 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1195 char *dup, *cur;
1196 int x = 0;
1197 int quoted = 0;
1198 int escaped = 0;
1199 int whitespace = 1;
1201 *trailingwhitespace = 0;
1202 if (s == NULL) /* invalid, though! */
1203 return NULL;
1204 /* make a copy to store the parsed string */
1205 if (!(dup = strdup(s)))
1206 return NULL;
1208 cur = dup;
1209 /* scan the original string copying into cur when needed */
1210 for (; *s ; s++) {
1211 if (x >= max - 1) {
1212 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1213 break;
1215 if (*s == '"' && !escaped) {
1216 quoted = !quoted;
1217 if (quoted && whitespace) {
1218 /* start a quoted string from previous whitespace: new argument */
1219 argv[x++] = cur;
1220 whitespace = 0;
1222 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1223 /* If we are not already in whitespace, and not in a quoted string or
1224 processing an escape sequence, and just entered whitespace, then
1225 finalize the previous argument and remember that we are in whitespace
1227 if (!whitespace) {
1228 *cur++ = '\0';
1229 whitespace = 1;
1231 } else if (*s == '\\' && !escaped) {
1232 escaped = 1;
1233 } else {
1234 if (whitespace) {
1235 /* we leave whitespace, and are not quoted. So it's a new argument */
1236 argv[x++] = cur;
1237 whitespace = 0;
1239 *cur++ = *s;
1240 escaped = 0;
1243 /* Null terminate */
1244 *cur++ = '\0';
1245 /* XXX put a NULL in the last argument, because some functions that take
1246 * the array may want a null-terminated array.
1247 * argc still reflects the number of non-NULL entries.
1249 argv[x] = NULL;
1250 *argc = x;
1251 *trailingwhitespace = whitespace;
1252 return dup;
1255 /*! \brief Return the number of unique matches for the generator */
1256 int ast_cli_generatornummatches(const char *text, const char *word)
1258 int matches = 0, i = 0;
1259 char *buf = NULL, *oldbuf = NULL;
1261 while ((buf = ast_cli_generator(text, word, i++))) {
1262 if (!oldbuf || strcmp(buf,oldbuf))
1263 matches++;
1264 if (oldbuf)
1265 free(oldbuf);
1266 oldbuf = buf;
1268 if (oldbuf)
1269 free(oldbuf);
1270 return matches;
1273 char **ast_cli_completion_matches(const char *text, const char *word)
1275 char **match_list = NULL, *retstr, *prevstr;
1276 size_t match_list_len, max_equal, which, i;
1277 int matches = 0;
1279 /* leave entry 0 free for the longest common substring */
1280 match_list_len = 1;
1281 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1282 if (matches + 1 >= match_list_len) {
1283 match_list_len <<= 1;
1284 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1285 return NULL;
1287 match_list[++matches] = retstr;
1290 if (!match_list)
1291 return match_list; /* NULL */
1293 /* Find the longest substring that is common to all results
1294 * (it is a candidate for completion), and store a copy in entry 0.
1296 prevstr = match_list[1];
1297 max_equal = strlen(prevstr);
1298 for (which = 2; which <= matches; which++) {
1299 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1300 continue;
1301 max_equal = i;
1304 if (!(retstr = ast_malloc(max_equal + 1)))
1305 return NULL;
1307 strncpy(retstr, match_list[1], max_equal);
1308 retstr[max_equal] = '\0';
1309 match_list[0] = retstr;
1311 /* ensure that the array is NULL terminated */
1312 if (matches + 1 >= match_list_len) {
1313 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1314 return NULL;
1316 match_list[matches + 1] = NULL;
1318 return match_list;
1321 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1323 char *argv[AST_MAX_ARGS];
1324 struct ast_cli_entry *e;
1325 struct cli_iterator i = { NULL, NULL };
1326 int x = 0, argindex, matchlen;
1327 int matchnum=0;
1328 char *ret = NULL;
1329 char matchstr[80] = "";
1330 int tws = 0;
1331 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1333 if (!dup) /* error */
1334 return NULL;
1335 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1336 /* rebuild the command, ignore tws */
1337 ast_join(matchstr, sizeof(matchstr)-1, argv);
1338 matchlen = strlen(matchstr);
1339 if (tws) {
1340 strcat(matchstr, " "); /* XXX */
1341 if (matchlen)
1342 matchlen++;
1344 if (lock)
1345 AST_LIST_LOCK(&helpers);
1346 while( !ret && (e = cli_next(&i)) ) {
1347 int lc = strlen(e->_full_cmd);
1348 if (e->_full_cmd[0] != '_' && lc > 0 && matchlen <= lc &&
1349 !strncasecmp(matchstr, e->_full_cmd, matchlen)) {
1350 /* Found initial part, return a copy of the next word... */
1351 if (e->cmda[argindex] && ++matchnum > state)
1352 ret = strdup(e->cmda[argindex]); /* we need a malloced string */
1353 } else if (e->generator && !strncasecmp(matchstr, e->_full_cmd, lc) && matchstr[lc] < 33) {
1354 /* We have a command in its entirity within us -- theoretically only one
1355 command can have this occur */
1356 ret = e->generator(matchstr, word, argindex, state);
1359 if (lock)
1360 AST_LIST_UNLOCK(&helpers);
1361 free(dup);
1362 return ret;
1365 char *ast_cli_generator(const char *text, const char *word, int state)
1367 return __ast_cli_generator(text, word, state, 1);
1370 int ast_cli_command(int fd, const char *s)
1372 char *argv[AST_MAX_ARGS];
1373 struct ast_cli_entry *e;
1374 int x;
1375 char *dup;
1376 int tws;
1378 if (!(dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws))) {
1379 ast_log(LOG_ERROR, "Memory allocation failure\n");
1380 return -1;
1383 /* We need at least one entry, or ignore */
1384 if (x > 0) {
1385 AST_LIST_LOCK(&helpers);
1386 e = find_cli(argv, 0);
1387 if (e)
1388 e->inuse++;
1389 AST_LIST_UNLOCK(&helpers);
1390 if (e) {
1391 switch(e->handler(fd, x, argv)) {
1392 case RESULT_SHOWUSAGE:
1393 if (e->usage)
1394 ast_cli(fd, "%s", e->usage);
1395 else
1396 ast_cli(fd, "Invalid usage, but no usage information available.\n");
1397 break;
1399 } else
1400 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1401 if (e) {
1402 AST_LIST_LOCK(&helpers);
1403 e->inuse--; /* XXX here an atomic dec would suffice */
1404 AST_LIST_UNLOCK(&helpers);
1407 free(dup);
1409 return 0;