add the other two files that should have been on this target... oops
[asterisk-bristuff.git] / cli.c
blob333286dad96e0bcb3c70113c2e9483e39bc1946f
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/manager.h"
48 #include "asterisk/utils.h"
49 #include "asterisk/app.h"
50 #include "asterisk/lock.h"
51 /* For rl_filename_completion */
52 #include "editline/readline/readline.h"
53 /* For module directory */
55 extern unsigned long global_fin, global_fout;
57 void ast_cli(int fd, char *fmt, ...)
59 char *stuff;
60 int res;
61 va_list ap;
63 va_start(ap, fmt);
64 res = vasprintf(&stuff, fmt, ap);
65 va_end(ap);
66 if (res == -1) {
67 ast_log(LOG_ERROR, "Memory allocation failure\n");
68 } else {
69 ast_carefulwrite(fd, stuff, strlen(stuff), 100);
70 free(stuff);
74 static AST_LIST_HEAD_STATIC(helpers, ast_cli_entry);
76 static char load_help[] =
77 "Usage: load <module name>\n"
78 " Loads the specified module into Asterisk.\n";
80 static char unload_help[] =
81 "Usage: unload [-f|-h] <module name>\n"
82 " Unloads the specified module from Asterisk. The -f\n"
83 " option causes the module to be unloaded even if it is\n"
84 " in use (may cause a crash) and the -h module causes the\n"
85 " module to be unloaded even if the module says it cannot, \n"
86 " which almost always will cause a crash.\n";
88 static char help_help[] =
89 "Usage: help [topic]\n"
90 " When called with a topic as an argument, displays usage\n"
91 " information on the given command. If called without a\n"
92 " topic, it provides a list of commands.\n";
94 static char chanlist_help[] =
95 "Usage: show channels [concise|verbose]\n"
96 " Lists currently defined channels and some information about them. If\n"
97 " 'concise' is specified, the format is abridged and in a more easily\n"
98 " machine parsable format. If 'verbose' is specified, the output includes\n"
99 " more and longer fields.\n";
101 static char reload_help[] =
102 "Usage: reload [module ...]\n"
103 " Reloads configuration files for all listed modules which support\n"
104 " reloading, or for all supported modules if none are listed.\n";
106 static char set_verbose_help[] =
107 "Usage: set verbose <level>\n"
108 " Sets level of verbose messages to be displayed. 0 means\n"
109 " no messages should be displayed. Equivalent to -v[v[v...]]\n"
110 " on startup\n";
112 static char set_debug_help[] =
113 "Usage: set debug <level>\n"
114 " Sets level of core debug messages to be displayed. 0 means\n"
115 " no messages should be displayed. Equivalent to -d[d[d...]]\n"
116 " on startup.\n";
118 static char softhangup_help[] =
119 "Usage: soft hangup <channel>\n"
120 " Request that a channel be hung up. The hangup takes effect\n"
121 " the next time the driver reads or writes from the channel\n";
123 static char group_show_channels_help[] =
124 "Usage: group show channels [pattern]\n"
125 " Lists all currently active channels with channel group(s) specified.\n"
126 " Optional regular expression pattern is matched to group names for each\n"
127 " channel.\n";
129 static char frog_help[] =
130 "Usage: frog [warp_factor]\n"
131 " Performs frog-in-a-blender calculations (Jacobsen Corollary)\n";
133 static int handle_load(int fd, int argc, char *argv[])
135 if (argc != 2)
136 return RESULT_SHOWUSAGE;
137 if (ast_load_resource(argv[1])) {
138 ast_cli(fd, "Unable to load module %s\n", argv[1]);
139 return RESULT_FAILURE;
141 return RESULT_SUCCESS;
144 static int handle_reload(int fd, int argc, char *argv[])
146 int x;
147 int res;
148 if (argc < 1)
149 return RESULT_SHOWUSAGE;
150 if (argc > 1) {
151 for (x=1;x<argc;x++) {
152 res = ast_module_reload(argv[x]);
153 switch(res) {
154 case 0:
155 ast_cli(fd, "No such module '%s'\n", argv[x]);
156 break;
157 case 1:
158 ast_cli(fd, "Module '%s' does not support reload\n", argv[x]);
159 break;
162 } else
163 ast_module_reload(NULL);
164 return RESULT_SUCCESS;
167 static int handle_set_verbose(int fd, int argc, char *argv[])
169 int val = 0;
170 int oldval = option_verbose;
172 /* "set verbose [atleast] N" */
173 if (argc == 3)
174 option_verbose = atoi(argv[2]);
175 else if (argc == 4) {
176 if (strcasecmp(argv[2], "atleast"))
177 return RESULT_SHOWUSAGE;
178 val = atoi(argv[3]);
179 if (val > option_verbose)
180 option_verbose = val;
181 } else
182 return RESULT_SHOWUSAGE;
183 if (oldval != option_verbose && option_verbose > 0)
184 ast_cli(fd, "Verbosity was %d and is now %d\n", oldval, option_verbose);
185 else if (oldval > 0 && option_verbose > 0)
186 ast_cli(fd, "Verbosity is at least %d\n", option_verbose);
187 else if (oldval > 0 && option_verbose == 0)
188 ast_cli(fd, "Verbosity is now OFF\n");
189 return RESULT_SUCCESS;
192 static int handle_set_debug(int fd, int argc, char *argv[])
194 int val = 0;
195 int oldval = option_debug;
197 /* "set debug [atleast] N" */
198 if (argc == 3)
199 option_debug = atoi(argv[2]);
200 else if (argc == 4) {
201 if (strcasecmp(argv[2], "atleast"))
202 return RESULT_SHOWUSAGE;
203 val = atoi(argv[3]);
204 if (val > option_debug)
205 option_debug = val;
206 } else
207 return RESULT_SHOWUSAGE;
208 if (oldval != option_debug && option_debug > 0)
209 ast_cli(fd, "Core debug was %d and is now %d\n", oldval, option_debug);
210 else if (oldval > 0 && option_debug > 0)
211 ast_cli(fd, "Core debug is at least %d\n", option_debug);
212 else if (oldval > 0 && option_debug == 0)
213 ast_cli(fd, "Core debug is now OFF\n");
214 return RESULT_SUCCESS;
217 static int handle_unload(int fd, int argc, char *argv[])
219 int x;
220 int force=AST_FORCE_SOFT;
221 if (argc < 2)
222 return RESULT_SHOWUSAGE;
223 for (x=1;x<argc;x++) {
224 if (argv[x][0] == '-') {
225 switch(argv[x][1]) {
226 case 'f':
227 force = AST_FORCE_FIRM;
228 break;
229 case 'h':
230 force = AST_FORCE_HARD;
231 break;
232 default:
233 return RESULT_SHOWUSAGE;
235 } else if (x != argc - 1)
236 return RESULT_SHOWUSAGE;
237 else if (ast_unload_resource(argv[x], force)) {
238 ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
239 return RESULT_FAILURE;
242 return RESULT_SUCCESS;
246 * Perform frong-in-a-blender calculations (Jacobsen Corollary)
249 static int handle_frog(int fd, int argc, char *argv[])
251 double warpone = 75139293848.0;
252 double warpfactor = 1.0;
254 if (argc > 2)
255 return RESULT_SHOWUSAGE;
256 if (argc > 1 && sscanf(argv[1], "%lf", &warpfactor) != 1)
257 return RESULT_SHOWUSAGE;
259 ast_cli(fd, "A frog in a blender with a base diameter of 3 inches going\n");
260 ast_cli(fd, "%.0f RPM will be travelling at warp factor %f,\n",
261 warpfactor * warpfactor * warpfactor * warpone, warpfactor);
262 ast_cli(fd, "based upon the Jacobsen Frog Corollary.\n");
263 return RESULT_SUCCESS;
267 #define MODLIST_FORMAT "%-30s %-40.40s %-10d\n"
268 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
270 AST_MUTEX_DEFINE_STATIC(climodentrylock);
271 static int climodentryfd = -1;
273 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
275 /* Comparing the like with the module */
276 if (strcasestr(module, like) ) {
277 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
278 return 1;
280 return 0;
283 static char modlist_help[] =
284 "Usage: show modules [like keyword]\n"
285 " Shows Asterisk modules currently in use, and usage statistics.\n";
287 static char uptime_help[] =
288 "Usage: show uptime [seconds]\n"
289 " Shows Asterisk uptime information.\n"
290 " The seconds word returns the uptime in seconds only.\n";
292 static void print_uptimestr(int fd, time_t timeval, const char *prefix, int printsec)
294 int x; /* the main part - years, weeks, etc. */
295 char timestr[256]="", *s = timestr;
296 size_t maxbytes = sizeof(timestr);
298 #define SECOND (1)
299 #define MINUTE (SECOND*60)
300 #define HOUR (MINUTE*60)
301 #define DAY (HOUR*24)
302 #define WEEK (DAY*7)
303 #define YEAR (DAY*365)
304 #define ESS(x) ((x == 1) ? "" : "s") /* plural suffix */
305 #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
306 if (timeval < 0) /* invalid, nothing to show */
307 return;
308 if (printsec) { /* plain seconds output */
309 ast_build_string(&s, &maxbytes, "%lu", (u_long)timeval);
310 timeval = 0; /* bypass the other cases */
312 if (timeval > YEAR) {
313 x = (timeval / YEAR);
314 timeval -= (x * YEAR);
315 ast_build_string(&s, &maxbytes, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval));
317 if (timeval > WEEK) {
318 x = (timeval / WEEK);
319 timeval -= (x * WEEK);
320 ast_build_string(&s, &maxbytes, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval));
322 if (timeval > DAY) {
323 x = (timeval / DAY);
324 timeval -= (x * DAY);
325 ast_build_string(&s, &maxbytes, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval));
327 if (timeval > HOUR) {
328 x = (timeval / HOUR);
329 timeval -= (x * HOUR);
330 ast_build_string(&s, &maxbytes, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval));
332 if (timeval > MINUTE) {
333 x = (timeval / MINUTE);
334 timeval -= (x * MINUTE);
335 ast_build_string(&s, &maxbytes, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval));
337 x = timeval;
338 if (x > 0)
339 ast_build_string(&s, &maxbytes, "%d second%s ", x, ESS(x));
340 if (timestr[0] != '\0')
341 ast_cli(fd, "%s: %s\n", prefix, timestr);
344 static int handle_showuptime(int fd, int argc, char *argv[])
346 /* 'show uptime [seconds]' */
347 time_t curtime = time(NULL);
348 int printsec = (argc == 3 && !strcasecmp(argv[2],"seconds"));
350 if (argc != 2 && !printsec)
351 return RESULT_SHOWUSAGE;
352 if (ast_startuptime)
353 print_uptimestr(fd, curtime - ast_startuptime, "System uptime", printsec);
354 if (ast_lastreloadtime)
355 print_uptimestr(fd, curtime - ast_lastreloadtime, "Last reload", printsec);
356 return RESULT_SUCCESS;
359 static int handle_modlist(int fd, int argc, char *argv[])
361 char *like = "";
362 if (argc == 3)
363 return RESULT_SHOWUSAGE;
364 else if (argc >= 4) {
365 if (strcmp(argv[2],"like"))
366 return RESULT_SHOWUSAGE;
367 like = argv[3];
370 ast_mutex_lock(&climodentrylock);
371 climodentryfd = fd; /* global, protected by climodentrylock */
372 ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
373 ast_cli(fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
374 climodentryfd = -1;
375 ast_mutex_unlock(&climodentrylock);
376 return RESULT_SUCCESS;
378 #undef MODLIST_FORMAT
379 #undef MODLIST_FORMAT2
381 static int handle_chanlist(int fd, int argc, char *argv[])
383 #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
384 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
385 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s\n"
386 #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"
387 #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"
389 struct ast_channel *c = NULL;
390 char durbuf[10] = "-";
391 char locbuf[40];
392 char appdata[40];
393 int duration;
394 int durh, durm, durs;
395 int numchans = 0, concise = 0, verbose = 0;
397 concise = (argc == 3 && (!strcasecmp(argv[2],"concise")));
398 verbose = (argc == 3 && (!strcasecmp(argv[2],"verbose")));
400 if (argc < 2 || argc > 3 || (argc == 3 && !concise && !verbose))
401 return RESULT_SHOWUSAGE;
403 if (!concise && !verbose)
404 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
405 else if (verbose)
406 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
407 "CallerID", "Duration", "Accountcode", "BridgedTo");
409 while ((c = ast_channel_walk_locked(c)) != NULL) {
410 struct ast_channel *bc = ast_bridged_channel(c);
411 if ((concise || verbose) && c->cdr && !ast_tvzero(c->cdr->start)) {
412 duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
413 if (verbose) {
414 durh = duration / 3600;
415 durm = (duration % 3600) / 60;
416 durs = duration % 60;
417 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
418 } else {
419 snprintf(durbuf, sizeof(durbuf), "%d", duration);
421 } else {
422 durbuf[0] = '\0';
424 if (concise) {
425 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
426 c->appl ? c->appl : "(None)", c->data ? c->data : "",
427 S_OR(c->cid.cid_num, ""),
428 c->accountcode ? c->accountcode : "", c->amaflags,
429 durbuf, bc ? bc->name : "(None)");
430 } else if (verbose) {
431 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
432 c->appl ? c->appl : "(None)", c->data ? S_OR(c->data, "(Empty)" ): "(None)",
433 S_OR(c->cid.cid_num, ""), durbuf,
434 c->accountcode ? c->accountcode : "", bc ? bc->name : "(None)");
435 } else {
436 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten))
437 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
438 else
439 strcpy(locbuf, "(None)");
440 if (c->appl)
441 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, c->data ? c->data : "");
442 else
443 strcpy(appdata, "(None)");
444 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
446 numchans++;
447 ast_channel_unlock(c);
449 if (!concise) {
450 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
451 if (option_maxcalls)
452 ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
453 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
454 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
455 else
456 ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
458 return RESULT_SUCCESS;
460 #undef FORMAT_STRING
461 #undef FORMAT_STRING2
462 #undef CONCISE_FORMAT_STRING
463 #undef VERBOSE_FORMAT_STRING
464 #undef VERBOSE_FORMAT_STRING2
467 static char showchan_help[] =
468 "Usage: show channel <channel>\n"
469 " Shows lots of information about the specified channel.\n";
471 static char debugchan_help[] =
472 "Usage: debug channel <channel>\n"
473 " Enables debugging on a specific channel.\n";
475 static char debuglevel_help[] =
476 "Usage: debug level <level> [filename]\n"
477 " Set debug to specified level (0 to disable). If filename\n"
478 "is specified, debugging will be limited to just that file.\n";
480 static char nodebugchan_help[] =
481 "Usage: no debug channel <channel>\n"
482 " Disables debugging on a specific channel.\n";
484 static char commandcomplete_help[] =
485 "Usage: _command complete \"<line>\" text state\n"
486 " This function is used internally to help with command completion and should.\n"
487 " never be called by the user directly.\n";
489 static char commandnummatches_help[] =
490 "Usage: _command nummatches \"<line>\" text \n"
491 " This function is used internally to help with command completion and should.\n"
492 " never be called by the user directly.\n";
494 static char commandmatchesarray_help[] =
495 "Usage: _command matchesarray \"<line>\" text \n"
496 " This function is used internally to help with command completion and should.\n"
497 " never be called by the user directly.\n";
499 static int handle_softhangup(int fd, int argc, char *argv[])
501 struct ast_channel *c=NULL;
502 if (argc != 3)
503 return RESULT_SHOWUSAGE;
504 c = ast_get_channel_by_name_locked(argv[2]);
505 if (c) {
506 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
507 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
508 ast_channel_unlock(c);
509 } else
510 ast_cli(fd, "%s is not a known channel\n", argv[2]);
511 return RESULT_SUCCESS;
514 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
516 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
518 char *buf, *obuf;
519 int buflen = 2048;
520 int len = 0;
521 char **matches;
522 int x, matchlen;
524 if (argc != 4)
525 return RESULT_SHOWUSAGE;
526 if (!(buf = ast_malloc(buflen)))
527 return RESULT_FAILURE;
528 buf[len] = '\0';
529 matches = ast_cli_completion_matches(argv[2], argv[3]);
530 if (matches) {
531 for (x=0; matches[x]; x++) {
532 matchlen = strlen(matches[x]) + 1;
533 if (len + matchlen >= buflen) {
534 buflen += matchlen * 3;
535 obuf = buf;
536 if (!(buf = ast_realloc(obuf, buflen)))
537 /* Memory allocation failure... Just free old buffer and be done */
538 free(obuf);
540 if (buf)
541 len += sprintf( buf + len, "%s ", matches[x]);
542 free(matches[x]);
543 matches[x] = NULL;
545 free(matches);
548 if (buf) {
549 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
550 free(buf);
551 } else
552 ast_cli(fd, "NULL\n");
554 return RESULT_SUCCESS;
559 static int handle_commandnummatches(int fd, int argc, char *argv[])
561 int matches = 0;
563 if (argc != 4)
564 return RESULT_SHOWUSAGE;
566 matches = ast_cli_generatornummatches(argv[2], argv[3]);
568 ast_cli(fd, "%d", matches);
570 return RESULT_SUCCESS;
573 static int handle_commandcomplete(int fd, int argc, char *argv[])
575 char *buf;
577 if (argc != 5)
578 return RESULT_SHOWUSAGE;
579 buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
580 if (buf) {
581 ast_cli(fd, buf);
582 free(buf);
583 } else
584 ast_cli(fd, "NULL\n");
585 return RESULT_SUCCESS;
588 static int handle_debuglevel(int fd, int argc, char *argv[])
590 int newlevel;
591 char *filename = "<any>";
592 if ((argc < 3) || (argc > 4))
593 return RESULT_SHOWUSAGE;
594 if (sscanf(argv[2], "%d", &newlevel) != 1)
595 return RESULT_SHOWUSAGE;
596 option_debug = newlevel;
597 if (argc == 4) {
598 filename = argv[3];
599 ast_copy_string(debug_filename, filename, sizeof(debug_filename));
600 } else {
601 debug_filename[0] = '\0';
603 ast_cli(fd, "Debugging level set to %d, file '%s'\n", newlevel, filename);
604 return RESULT_SUCCESS;
607 /* XXX todo: merge next two functions!!! */
608 static int handle_debugchan(int fd, int argc, char *argv[])
610 struct ast_channel *c=NULL;
611 int is_all;
613 /* 'debug channel {all|chan_id}' */
614 if (argc != 3)
615 return RESULT_SHOWUSAGE;
617 is_all = !strcasecmp("all", argv[2]);
618 if (is_all) {
619 global_fin |= DEBUGCHAN_FLAG;
620 global_fout |= DEBUGCHAN_FLAG;
621 c = ast_channel_walk_locked(NULL);
622 } else {
623 c = ast_get_channel_by_name_locked(argv[2]);
624 if (c == NULL)
625 ast_cli(fd, "No such channel %s\n", argv[2]);
627 while (c) {
628 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
629 c->fin |= DEBUGCHAN_FLAG;
630 c->fout |= DEBUGCHAN_FLAG;
631 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
633 ast_channel_unlock(c);
634 if (!is_all)
635 break;
636 c = ast_channel_walk_locked(c);
638 ast_cli(fd, "Debugging on new channels is enabled\n");
639 return RESULT_SUCCESS;
642 static int handle_nodebugchan(int fd, int argc, char *argv[])
644 struct ast_channel *c=NULL;
645 int is_all;
646 /* 'no debug channel {all|chan_id}' */
647 if (argc != 4)
648 return RESULT_SHOWUSAGE;
649 is_all = !strcasecmp("all", argv[3]);
650 if (is_all) {
651 global_fin &= ~DEBUGCHAN_FLAG;
652 global_fout &= ~DEBUGCHAN_FLAG;
653 c = ast_channel_walk_locked(NULL);
654 } else {
655 c = ast_get_channel_by_name_locked(argv[3]);
656 if (c == NULL)
657 ast_cli(fd, "No such channel %s\n", argv[3]);
659 while(c) {
660 if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
661 c->fin &= ~DEBUGCHAN_FLAG;
662 c->fout &= ~DEBUGCHAN_FLAG;
663 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
665 ast_channel_unlock(c);
666 if (!is_all)
667 break;
668 c = ast_channel_walk_locked(c);
670 ast_cli(fd, "Debugging on new channels is disabled\n");
671 return RESULT_SUCCESS;
674 static int handle_showchan(int fd, int argc, char *argv[])
676 struct ast_channel *c=NULL;
677 struct timeval now;
678 char buf[2048];
679 char cdrtime[256];
680 char nf[256], wf[256], rf[256];
681 long elapsed_seconds=0;
682 int hour=0, min=0, sec=0;
684 if (argc != 3)
685 return RESULT_SHOWUSAGE;
686 now = ast_tvnow();
687 c = ast_get_channel_by_name_locked(argv[2]);
688 if (!c) {
689 ast_cli(fd, "%s is not a known channel\n", argv[2]);
690 return RESULT_SUCCESS;
692 if(c->cdr) {
693 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
694 hour = elapsed_seconds / 3600;
695 min = (elapsed_seconds % 3600) / 60;
696 sec = elapsed_seconds % 60;
697 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
698 } else
699 strcpy(cdrtime, "N/A");
700 ast_cli(fd,
701 " -- General --\n"
702 " Name: %s\n"
703 " Type: %s\n"
704 " UniqueID: %s\n"
705 " Caller ID: %s\n"
706 " Caller ID Name: %s\n"
707 " DNID Digits: %s\n"
708 " State: %s (%d)\n"
709 " Rings: %d\n"
710 " NativeFormats: %s\n"
711 " WriteFormat: %s\n"
712 " ReadFormat: %s\n"
713 "1st File Descriptor: %d\n"
714 " Frames in: %d%s\n"
715 " Frames out: %d%s\n"
716 " Time to Hangup: %ld\n"
717 " Elapsed Time: %s\n"
718 " Direct Bridge: %s\n"
719 "Indirect Bridge: %s\n"
720 " -- PBX --\n"
721 " Context: %s\n"
722 " Extension: %s\n"
723 " Priority: %d\n"
724 " Call Group: %d\n"
725 " Pickup Group: %d\n"
726 " Application: %s\n"
727 " Data: %s\n"
728 " Blocking in: %s\n",
729 c->name, c->tech->type, c->uniqueid,
730 S_OR(c->cid.cid_num, "(N/A)"),
731 S_OR(c->cid.cid_name, "(N/A)"),
732 S_OR(c->cid.cid_dnid, "(N/A)"), ast_state2str(c->_state), c->_state, c->rings,
733 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats),
734 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat),
735 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
736 c->fds[0],
737 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
738 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
739 (long)c->whentohangup,
740 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>",
741 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
742 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
743 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
745 if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
746 ast_cli(fd," Variables:\n%s\n",buf);
747 if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
748 ast_cli(fd," CDR Variables:\n%s\n",buf);
750 ast_channel_unlock(c);
751 return RESULT_SUCCESS;
755 * helper function to generate CLI matches from a fixed set of values.
756 * A NULL word is acceptable.
758 char *ast_cli_complete(const char *word, char *const choices[], int state)
760 int i, which = 0, len;
761 len = ast_strlen_zero(word) ? 0 : strlen(word);
763 for (i = 0; choices[i]; i++) {
764 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
765 return ast_strdup(choices[i]);
767 return NULL;
770 static char *complete_show_channels(const char *line, const char *word, int pos, int state)
772 static char *choices[] = { "concise", "verbose", NULL };
774 return (pos != 2) ? NULL : ast_cli_complete(word, choices, state);
777 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
779 struct ast_channel *c = NULL;
780 int which = 0;
781 int wordlen;
782 char notfound = '\0';
783 char *ret = &notfound; /* so NULL can break the loop */
785 if (pos != rpos)
786 return NULL;
788 wordlen = strlen(word);
790 while (ret == &notfound && (c = ast_channel_walk_locked(c))) {
791 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
792 ret = ast_strdup(c->name);
793 ast_channel_unlock(c);
795 return ret == &notfound ? NULL : ret;
798 static char *complete_ch_3(const char *line, const char *word, int pos, int state)
800 return ast_complete_channels(line, word, pos, state, 2);
803 static char *complete_ch_4(const char *line, const char *word, int pos, int state)
805 return ast_complete_channels(line, word, pos, state, 3);
808 static char *complete_mod_2(const char *line, const char *word, int pos, int state)
810 return ast_module_helper(line, word, pos, state, 1, 1);
813 static char *complete_mod_4(const char *line, const char *word, int pos, int state)
815 return ast_module_helper(line, word, pos, state, 3, 0);
818 static char *complete_fn(const char *line, const char *word, int pos, int state)
820 char *c;
821 char filename[256];
823 if (pos != 1)
824 return NULL;
826 if (word[0] == '/')
827 ast_copy_string(filename, word, sizeof(filename));
828 else
829 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
831 c = filename_completion_function(filename, state);
833 if (c && word[0] != '/')
834 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
836 return c ? strdup(c) : c;
839 static int group_show_channels(int fd, int argc, char *argv[])
841 #define FORMAT_STRING "%-25s %-20s %-20s\n"
843 struct ast_channel *c = NULL;
844 int numchans = 0;
845 struct ast_var_t *current;
846 struct varshead *headp;
847 regex_t regexbuf;
848 int havepattern = 0;
850 if (argc < 3 || argc > 4)
851 return RESULT_SHOWUSAGE;
853 if (argc == 4) {
854 if (regcomp(&regexbuf, argv[3], REG_EXTENDED | REG_NOSUB))
855 return RESULT_SHOWUSAGE;
856 havepattern = 1;
859 ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
860 while ( (c = ast_channel_walk_locked(c)) != NULL) {
861 headp=&c->varshead;
862 AST_LIST_TRAVERSE(headp,current,entries) {
863 if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
864 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
865 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
866 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
867 numchans++;
869 } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
870 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
871 ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
872 numchans++;
876 numchans++;
877 ast_channel_unlock(c);
880 if (havepattern)
881 regfree(&regexbuf);
883 ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
884 return RESULT_SUCCESS;
885 #undef FORMAT_STRING
888 static int handle_help(int fd, int argc, char *argv[]);
890 static char * complete_help(const char *text, const char *word, int pos, int state)
892 /* skip first 4 or 5 chars, "help "*/
893 int l = strlen(text);
895 if (l > 5)
896 l = 5;
897 text += l;
898 /* XXX watch out, should stop to the non-generator parts */
899 return __ast_cli_generator(text, word, state, 0);
902 static struct ast_cli_entry builtins[] = {
903 /* Keep alphabetized, with longer matches first (example: abcd before abc) */
904 { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
905 { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
906 { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
907 { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch_3 },
908 { { "debug", "level", NULL }, handle_debuglevel, "Set global debug level", debuglevel_help },
909 { { "frog", NULL }, handle_frog,"Perform frog-in-a-blender calculations", frog_help },
910 { { "group", "show", "channels", NULL }, group_show_channels, "Show active channels with group(s)", group_show_channels_help},
911 { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help, complete_help },
912 { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
913 { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch_4 },
914 { { "reload", NULL }, handle_reload, "Reload configuration", reload_help, complete_mod_2 },
915 { { "set", "debug", NULL }, handle_set_debug, "Set level of debug chattiness", set_debug_help },
916 { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
917 { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch_3 },
918 { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help, complete_show_channels },
919 { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
920 { { "show", "modules", "like", NULL }, handle_modlist, "List modules and info", modlist_help, complete_mod_4 },
921 { { "show", "uptime", NULL }, handle_showuptime, "Show uptime information", uptime_help },
922 { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch_3 },
923 { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
924 { { NULL }, NULL, NULL, NULL }
927 /*! \brief initialize the _full_cmd string in * each of the builtins. */
928 void ast_builtins_init(void)
930 struct ast_cli_entry *e;
932 for (e = builtins; e->cmda[0] != NULL; e++) {
933 char buf[80];
934 ast_join(buf, sizeof(buf), e->cmda);
935 e->_full_cmd = strdup(buf);
936 if (!e->_full_cmd)
937 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
942 * We have two sets of commands: builtins are stored in a
943 * NULL-terminated array of ast_cli_entry, whereas external
944 * commands are in a list.
945 * When navigating, we need to keep two pointers and get
946 * the next one in lexicographic order. For the purpose,
947 * we use a structure.
950 struct cli_iterator {
951 struct ast_cli_entry *builtins;
952 struct ast_cli_entry *helpers;
955 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
957 struct ast_cli_entry *e;
959 if (i->builtins == NULL && i->helpers == NULL) {
960 /* initialize */
961 i->builtins = builtins;
962 i->helpers = AST_LIST_FIRST(&helpers);
964 e = i->builtins; /* temporary */
965 if (!e->cmda[0] || (i->helpers &&
966 strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
967 /* Use helpers */
968 e = i->helpers;
969 if (e)
970 i->helpers = AST_LIST_NEXT(e, list);
971 } else { /* use builtin. e is already set */
972 (i->builtins)++; /* move to next */
974 return e;
978 * \brief locate a cli command in the 'helpers' list (which must be locked).
979 * exact has 3 values:
980 * 0 returns if the search key is equal or longer than the entry.
981 * -1 true if the mismatch is on the last word XXX not true!
982 * 1 true only on complete, exact match.
984 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
986 int matchlen = -1; /* length of longest match so far */
987 struct ast_cli_entry *cand = NULL, *e=NULL;
988 struct cli_iterator i = { NULL, NULL};
990 while( (e = cli_next(&i)) ) {
991 int y;
992 for (y = 0 ; cmds[y] && e->cmda[y]; y++) {
993 if (strcasecmp(e->cmda[y], cmds[y]))
994 break;
996 if (e->cmda[y] == NULL) { /* no more words in candidate */
997 if (cmds[y] == NULL) /* this is an exact match, cannot do better */
998 break;
999 /* here the search key is longer than the candidate */
1000 if (match_type != 0) /* but we look for almost exact match... */
1001 continue; /* so we skip this one. */
1002 /* otherwise we like it (case 0) */
1003 } else { /* still words in candidate */
1004 if (cmds[y] == NULL) /* search key is shorter, not good */
1005 continue;
1006 /* if we get here, both words exist but there is a mismatch */
1007 if (match_type == 0) /* not the one we look for */
1008 continue;
1009 if (match_type == 1) /* not the one we look for */
1010 continue;
1011 if (cmds[y+1] != NULL || e->cmda[y+1] != NULL) /* not the one we look for */
1012 continue;
1013 /* we are in case match_type == -1 and mismatch on last word */
1015 if (cand == NULL || y > matchlen) /* remember the candidate */
1016 cand = e;
1018 return e ? e : cand;
1021 static char *find_best(char *argv[])
1023 static char cmdline[80];
1024 int x;
1025 /* See how close we get, then print the candidate */
1026 char *myargv[AST_MAX_CMD_LEN];
1027 for (x=0;x<AST_MAX_CMD_LEN;x++)
1028 myargv[x]=NULL;
1029 AST_LIST_LOCK(&helpers);
1030 for (x=0;argv[x];x++) {
1031 myargv[x] = argv[x];
1032 if (!find_cli(myargv, -1))
1033 break;
1035 AST_LIST_UNLOCK(&helpers);
1036 ast_join(cmdline, sizeof(cmdline), myargv);
1037 return cmdline;
1040 int ast_cli_unregister(struct ast_cli_entry *e)
1042 if (e->inuse) {
1043 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1044 } else {
1045 AST_LIST_LOCK(&helpers);
1046 AST_LIST_REMOVE(&helpers, e, list);
1047 AST_LIST_UNLOCK(&helpers);
1049 return 0;
1052 int ast_cli_register(struct ast_cli_entry *e)
1054 struct ast_cli_entry *cur;
1055 char fulle[80] ="";
1056 int lf, ret = -1;
1058 ast_join(fulle, sizeof(fulle), e->cmda);
1059 AST_LIST_LOCK(&helpers);
1061 if (find_cli(e->cmda, 1)) {
1062 AST_LIST_UNLOCK(&helpers);
1063 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1064 goto done;
1066 e->_full_cmd = ast_strdup(fulle);
1067 if (!e->_full_cmd)
1068 goto done;
1069 lf = strlen(fulle);
1070 AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1071 int len = strlen(cur->_full_cmd);
1072 if (lf < len)
1073 len = lf;
1074 if (strncasecmp(fulle, cur->_full_cmd, len) < 0) {
1075 AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list);
1076 break;
1079 AST_LIST_TRAVERSE_SAFE_END;
1081 if (!cur)
1082 AST_LIST_INSERT_TAIL(&helpers, e, list);
1083 ret = 0; /* success */
1085 done:
1086 AST_LIST_UNLOCK(&helpers);
1088 return ret;
1092 * register/unregister an array of entries.
1094 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1096 int i;
1098 for (i = 0; i < len; i++)
1099 ast_cli_register(e + i);
1102 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1104 int i;
1106 for (i = 0; i < len; i++)
1107 ast_cli_unregister(e + i);
1111 /*! \brief helper for help_workhorse and final part of
1112 * handle_help. if locked = 0 it's just help_workhorse,
1113 * otherwise assume the list is already locked and print
1114 * an error message if not found.
1116 static int help1(int fd, char *match[], int locked)
1118 char matchstr[80] = "";
1119 struct ast_cli_entry *e;
1120 int len = 0;
1121 int found = 0;
1122 struct cli_iterator i = { NULL, NULL};
1124 if (match) {
1125 ast_join(matchstr, sizeof(matchstr), match);
1126 len = strlen(matchstr);
1128 if (!locked)
1129 AST_LIST_LOCK(&helpers);
1130 while ( (e = cli_next(&i)) ) {
1131 /* Hide commands that start with '_' */
1132 if (e->_full_cmd[0] == '_')
1133 continue;
1134 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1135 continue;
1136 ast_cli(fd, "%25.25s %s\n", e->_full_cmd, e->summary);
1137 found++;
1139 AST_LIST_UNLOCK(&helpers);
1140 if (!locked && !found && matchstr[0])
1141 ast_cli(fd, "No such command '%s'.\n", matchstr);
1142 return 0;
1145 static int help_workhorse(int fd, char *match[])
1147 return help1(fd, match, 0 /* do not print errors */);
1150 static int handle_help(int fd, int argc, char *argv[])
1152 char fullcmd[80];
1153 struct ast_cli_entry *e;
1155 if (argc < 1)
1156 return RESULT_SHOWUSAGE;
1157 if (argc == 1)
1158 return help_workhorse(fd, NULL);
1160 AST_LIST_LOCK(&helpers);
1161 e = find_cli(argv + 1, 1); /* try exact match first */
1162 if (!e)
1163 return help1(fd, argv + 1, 1 /* locked */);
1164 if (e->usage)
1165 ast_cli(fd, "%s", e->usage);
1166 else {
1167 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1168 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1170 AST_LIST_UNLOCK(&helpers);
1171 return RESULT_SUCCESS;
1174 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1176 char *dup, *cur;
1177 int x = 0;
1178 int quoted = 0;
1179 int escaped = 0;
1180 int whitespace = 1;
1182 *trailingwhitespace = 0;
1183 if (s == NULL) /* invalid, though! */
1184 return NULL;
1185 /* make a copy to store the parsed string */
1186 if (!(dup = strdup(s)))
1187 return NULL;
1189 cur = dup;
1190 /* scan the original string copying into cur when needed */
1191 for (; *s ; s++) {
1192 if (x >= max - 1) {
1193 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1194 break;
1196 if (*s == '"' && !escaped) {
1197 quoted = !quoted;
1198 if (quoted && whitespace) {
1199 /* start a quoted string from previous whitespace: new argument */
1200 argv[x++] = cur;
1201 whitespace = 0;
1203 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1204 /* If we are not already in whitespace, and not in a quoted string or
1205 processing an escape sequence, and just entered whitespace, then
1206 finalize the previous argument and remember that we are in whitespace
1208 if (!whitespace) {
1209 *cur++ = '\0';
1210 whitespace = 1;
1212 } else if (*s == '\\' && !escaped) {
1213 escaped = 1;
1214 } else {
1215 if (whitespace) {
1216 /* we leave whitespace, and are not quoted. So it's a new argument */
1217 argv[x++] = cur;
1218 whitespace = 0;
1220 *cur++ = *s;
1221 escaped = 0;
1224 /* Null terminate */
1225 *cur++ = '\0';
1226 /* XXX put a NULL in the last argument, because some functions that take
1227 * the array may want a null-terminated array.
1228 * argc still reflects the number of non-NULL entries.
1230 argv[x] = NULL;
1231 *argc = x;
1232 *trailingwhitespace = whitespace;
1233 return dup;
1236 /*! \brief Return the number of unique matches for the generator */
1237 int ast_cli_generatornummatches(const char *text, const char *word)
1239 int matches = 0, i = 0;
1240 char *buf = NULL, *oldbuf = NULL;
1242 while ((buf = ast_cli_generator(text, word, i++))) {
1243 if (!oldbuf || strcmp(buf,oldbuf))
1244 matches++;
1245 if (oldbuf)
1246 free(oldbuf);
1247 oldbuf = buf;
1249 if (oldbuf)
1250 free(oldbuf);
1251 return matches;
1254 char **ast_cli_completion_matches(const char *text, const char *word)
1256 char **match_list = NULL, *retstr, *prevstr;
1257 size_t match_list_len, max_equal, which, i;
1258 int matches = 0;
1260 /* leave entry 0 free for the longest common substring */
1261 match_list_len = 1;
1262 while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1263 if (matches + 1 >= match_list_len) {
1264 match_list_len <<= 1;
1265 if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1266 return NULL;
1268 match_list[++matches] = retstr;
1271 if (!match_list)
1272 return match_list; /* NULL */
1274 /* Find the longest substring that is common to all results
1275 * (it is a candidate for completion), and store a copy in entry 0.
1277 prevstr = match_list[1];
1278 max_equal = strlen(prevstr);
1279 for (which = 2; which <= matches; which++) {
1280 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1281 continue;
1282 max_equal = i;
1285 if (!(retstr = ast_malloc(max_equal + 1)))
1286 return NULL;
1288 strncpy(retstr, match_list[1], max_equal);
1289 retstr[max_equal] = '\0';
1290 match_list[0] = retstr;
1292 /* ensure that the array is NULL terminated */
1293 if (matches + 1 >= match_list_len) {
1294 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1295 return NULL;
1297 match_list[matches + 1] = NULL;
1299 return match_list;
1302 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1304 char *argv[AST_MAX_ARGS];
1305 struct ast_cli_entry *e;
1306 struct cli_iterator i = { NULL, NULL };
1307 int x = 0, argindex, matchlen;
1308 int matchnum=0;
1309 char *ret = NULL;
1310 char matchstr[80] = "";
1311 int tws;
1312 char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1314 if (!dup) /* error */
1315 return NULL;
1316 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1317 /* rebuild the command, ignore tws */
1318 ast_join(matchstr, sizeof(matchstr)-1, argv);
1319 if (tws)
1320 strcat(matchstr, " "); /* XXX */
1321 matchlen = strlen(matchstr);
1322 if (lock)
1323 AST_LIST_LOCK(&helpers);
1324 while( !ret && (e = cli_next(&i)) ) {
1325 int lc = strlen(e->_full_cmd);
1326 if (e->_full_cmd[0] != '_' && lc > 0 && matchlen <= lc &&
1327 !strncasecmp(matchstr, e->_full_cmd, matchlen)) {
1328 /* Found initial part, return a copy of the next word... */
1329 if (e->cmda[argindex] && ++matchnum > state)
1330 ret = strdup(e->cmda[argindex]); /* we need a malloced string */
1331 } else if (e->generator && !strncasecmp(matchstr, e->_full_cmd, lc) && matchstr[lc] < 33) {
1332 /* We have a command in its entirity within us -- theoretically only one
1333 command can have this occur */
1334 ret = e->generator(matchstr, word, argindex, state);
1337 if (lock)
1338 AST_LIST_UNLOCK(&helpers);
1339 free(dup);
1340 return ret;
1343 char *ast_cli_generator(const char *text, const char *word, int state)
1345 return __ast_cli_generator(text, word, state, 1);
1348 int ast_cli_command(int fd, const char *s)
1350 char *argv[AST_MAX_ARGS];
1351 struct ast_cli_entry *e;
1352 int x;
1353 char *dup;
1354 int tws;
1356 if (!(dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws))) {
1357 ast_log(LOG_ERROR, "Memory allocation failure\n");
1358 return -1;
1361 /* We need at least one entry, or ignore */
1362 if (x > 0) {
1363 AST_LIST_LOCK(&helpers);
1364 e = find_cli(argv, 0);
1365 if (e)
1366 e->inuse++;
1367 AST_LIST_UNLOCK(&helpers);
1368 if (e) {
1369 switch(e->handler(fd, x, argv)) {
1370 case RESULT_SHOWUSAGE:
1371 if (e->usage)
1372 ast_cli(fd, "%s", e->usage);
1373 else
1374 ast_cli(fd, "Invalid usage, but no usage information available.\n");
1375 break;
1377 } else
1378 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1379 if (e) {
1380 AST_LIST_LOCK(&helpers);
1381 e->inuse--; /* XXX here an atomic dec would suffice */
1382 AST_LIST_UNLOCK(&helpers);
1385 free(dup);
1387 return 0;