fa6a78909833d699d6518f5812423f3b6a954ec8
[asterisk/asterisk.git] / main / cli.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  *
21  * \brief Standard Command Line Interface
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
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>
38
39 #include "asterisk/logger.h"
40 #include "asterisk/options.h"
41 #include "asterisk/cli.h"
42 #include "asterisk/linkedlists.h"
43 #include "asterisk/module.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/app.h"
48 #include "asterisk/lock.h"
49 #include "editline/readline/readline.h"
50 #include "asterisk/threadstorage.h"
51
52 extern unsigned long global_fin, global_fout;
53
54 AST_THREADSTORAGE(ast_cli_buf);
55
56 /*! \brief Initial buffer size for resulting strings in ast_cli() */
57 #define AST_CLI_INITLEN   256
58
59 void ast_cli(int fd, char *fmt, ...)
60 {
61         int res;
62         struct ast_dynamic_str *buf;
63         va_list ap;
64
65         if (!(buf = ast_dynamic_str_thread_get(&ast_cli_buf, AST_CLI_INITLEN)))
66                 return;
67
68         va_start(ap, fmt);
69         res = ast_dynamic_str_thread_set_va(&buf, 0, &ast_cli_buf, fmt, ap);
70         va_end(ap);
71
72         if (res != AST_DYNSTR_BUILD_FAILED)
73                 ast_carefulwrite(fd, buf->str, strlen(buf->str), 100);
74 }
75
76 static AST_LIST_HEAD_STATIC(helpers, ast_cli_entry);
77
78 static char load_help[] = 
79 "Usage: load <module name>\n"
80 "       Loads the specified module into Asterisk.\n";
81
82 static char unload_help[] = 
83 "Usage: unload [-f|-h] <module name>\n"
84 "       Unloads the specified module from Asterisk. The -f\n"
85 "       option causes the module to be unloaded even if it is\n"
86 "       in use (may cause a crash) and the -h module causes the\n"
87 "       module to be unloaded even if the module says it cannot, \n"
88 "       which almost always will cause a crash.\n";
89
90 static char help_help[] =
91 "Usage: help [topic]\n"
92 "       When called with a topic as an argument, displays usage\n"
93 "       information on the given command. If called without a\n"
94 "       topic, it provides a list of commands.\n";
95
96 static char chanlist_help[] = 
97 "Usage: core show channels [concise|verbose]\n"
98 "       Lists currently defined channels and some information about them. If\n"
99 "       'concise' is specified, the format is abridged and in a more easily\n"
100 "       machine parsable format. If 'verbose' is specified, the output includes\n"
101 "       more and longer fields.\n";
102
103 static char reload_help[] = 
104 "Usage: reload [module ...]\n"
105 "       Reloads configuration files for all listed modules which support\n"
106 "       reloading, or for all supported modules if none are listed.\n";
107
108 static char verbose_help[] = 
109 "Usage: core set verbose <level>\n"
110 "       Sets level of verbose messages to be displayed.  0 means\n"
111 "       no messages should be displayed. Equivalent to -v[v[v...]]\n"
112 "       on startup\n";
113
114 static char debug_help[] = 
115 "Usage: core set debug <level> [filename]\n"
116 "       Sets level of core debug messages to be displayed.  0 means\n"
117 "       no messages should be displayed.  Equivalent to -d[d[d...]]\n"
118 "       on startup.  If filename is specified, debugging will be\n"
119 "       limited to just that file.\n";
120
121 static char nodebug_help[] = 
122 "Usage: core set no debug\n"
123 "       Turns off core debug messages.\n";
124
125 static char logger_mute_help[] = 
126 "Usage: logger mute\n"
127 "       Disables logging output to the current console, making it possible to\n"
128 "       gather information without being disturbed by scrolling lines.\n";
129
130 static char softhangup_help[] =
131 "Usage: soft hangup <channel>\n"
132 "       Request that a channel be hung up. The hangup takes effect\n"
133 "       the next time the driver reads or writes from the channel\n";
134
135 static char group_show_channels_help[] = 
136 "Usage: group show channels [pattern]\n"
137 "       Lists all currently active channels with channel group(s) specified.\n"
138 "       Optional regular expression pattern is matched to group names for each\n"
139 "       channel.\n";
140
141 static int handle_load(int fd, int argc, char *argv[])
142 {
143         if (argc != 2)
144                 return RESULT_SHOWUSAGE;
145         if (ast_load_resource(argv[1])) {
146                 ast_cli(fd, "Unable to load module %s\n", argv[1]);
147                 return RESULT_FAILURE;
148         }
149         return RESULT_SUCCESS;
150 }
151
152 static int handle_reload(int fd, int argc, char *argv[])
153 {
154         int x;
155         int res;
156         if (argc < 1)
157                 return RESULT_SHOWUSAGE;
158         if (argc > 1) { 
159                 for (x=1;x<argc;x++) {
160                         res = ast_module_reload(argv[x]);
161                         switch(res) {
162                         case 0:
163                                 ast_cli(fd, "No such module '%s'\n", argv[x]);
164                                 break;
165                         case 1:
166                                 ast_cli(fd, "Module '%s' does not support reload\n", argv[x]);
167                                 break;
168                         }
169                 }
170         } else
171                 ast_module_reload(NULL);
172         return RESULT_SUCCESS;
173 }
174
175 static int handle_verbose(int fd, int argc, char *argv[])
176 {
177         int oldval = option_verbose;
178         int newlevel;
179         int atleast = 0;
180
181         if ((argc < 4) || (argc > 5))
182                 return RESULT_SHOWUSAGE;
183
184         if (!strcasecmp(argv[3], "atleast"))
185                 atleast = 1;
186
187         if (!atleast) {
188                 if (argc > 4)
189                         return RESULT_SHOWUSAGE;
190
191                 option_verbose = atoi(argv[3]);
192         } else {
193                 if (argc < 5)
194                         return RESULT_SHOWUSAGE;
195
196                 newlevel = atoi(argv[4]);
197                 if (newlevel > option_verbose)
198                         option_verbose = newlevel;
199         }
200         if (oldval > 0 && option_verbose == 0)
201                 ast_cli(fd, "Verbosity is now OFF\n");
202         else if (option_verbose > 0) {
203                 if (oldval == option_verbose)
204                         ast_cli(fd, "Verbosity is at least %d\n", option_verbose);
205                 else
206                         ast_cli(fd, "Verbosity was %d and is now %d\n", oldval, option_verbose);
207         }
208
209         return RESULT_SUCCESS;
210 }
211
212 static int handle_debug(int fd, int argc, char *argv[])
213 {
214         int oldval = option_debug;
215         int newlevel;
216         int atleast = 0;
217         char *filename = '\0';
218
219         if ((argc < 4) || (argc > 6))
220                 return RESULT_SHOWUSAGE;
221
222         if (!strcasecmp(argv[3], "atleast"))
223                 atleast = 1;
224
225         if (!atleast) {
226                 if (argc > 5)
227                         return RESULT_SHOWUSAGE;
228
229                 if (sscanf(argv[3], "%d", &newlevel) != 1)
230                         return RESULT_SHOWUSAGE;
231
232                 if (argc == 4) {
233                         debug_filename[0] = '\0';
234                 } else {
235                         filename = argv[4];
236                         ast_copy_string(debug_filename, filename, sizeof(debug_filename));
237                 }
238
239                 option_debug = newlevel;
240         } else {
241                 if (argc < 5 || argc > 6)
242                         return RESULT_SHOWUSAGE;
243
244                 if (sscanf(argv[4], "%d", &newlevel) != 1)
245                         return RESULT_SHOWUSAGE;
246
247                 if (argc == 6) {
248                         debug_filename[0] = '\0';
249                 } else {
250                         filename = argv[4];
251                         ast_copy_string(debug_filename, filename, sizeof(debug_filename));
252                 }
253
254                 if (newlevel > option_debug)
255                         option_debug = newlevel;
256         }
257
258         if (oldval > 0 && option_debug == 0)
259                 ast_cli(fd, "Core debug is now OFF\n");
260         else if (option_debug > 0) {
261                 if (filename) {
262                         if (oldval == option_debug)
263                                 ast_cli(fd, "Core debug is at least %d, file '%s'\n", option_debug, filename);
264                         else
265                                 ast_cli(fd, "Core debug was %d and is now %d, file '%s'\n", oldval, option_debug, filename);
266                 } else {
267                         if (oldval == option_debug)
268                                 ast_cli(fd, "Core debug is at least %d\n", option_debug);
269                         else
270                                 ast_cli(fd, "Core debug was %d and is now %d\n", oldval, option_debug);
271                 }
272         }
273
274         return RESULT_SUCCESS;
275 }
276
277 static int handle_nodebug(int fd, int argc, char *argv[])
278 {
279         int oldval = option_debug;
280         if (argc != 2)
281                 return RESULT_SHOWUSAGE;
282
283         option_debug = 0;
284         debug_filename[0] = '\0';
285
286         if (oldval > 0)
287                 ast_cli(fd, "Core debug is now OFF\n");
288         return RESULT_SUCCESS;
289 }
290
291 static int handle_logger_mute(int fd, int argc, char *argv[])
292 {
293         if (argc != 2)
294                 return RESULT_SHOWUSAGE;
295         ast_console_toggle_mute(fd);
296         return RESULT_SUCCESS;
297 }
298
299 static int handle_unload(int fd, int argc, char *argv[])
300 {
301         int x;
302         int force=AST_FORCE_SOFT;
303         if (argc < 2)
304                 return RESULT_SHOWUSAGE;
305         for (x=1;x<argc;x++) {
306                 if (argv[x][0] == '-') {
307                         switch(argv[x][1]) {
308                         case 'f':
309                                 force = AST_FORCE_FIRM;
310                                 break;
311                         case 'h':
312                                 force = AST_FORCE_HARD;
313                                 break;
314                         default:
315                                 return RESULT_SHOWUSAGE;
316                         }
317                 } else if (x !=  argc - 1) 
318                         return RESULT_SHOWUSAGE;
319                 else if (ast_unload_resource(argv[x], force)) {
320                         ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
321                         return RESULT_FAILURE;
322                 }
323         }
324         return RESULT_SUCCESS;
325 }
326
327 #define MODLIST_FORMAT  "%-30s %-40.40s %-10d\n"
328 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
329
330 AST_MUTEX_DEFINE_STATIC(climodentrylock);
331 static int climodentryfd = -1;
332
333 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
334 {
335         /* Comparing the like with the module */
336         if (strcasestr(module, like) ) {
337                 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
338                 return 1;
339         } 
340         return 0;
341 }
342
343 static char modlist_help[] =
344 "Usage: core show modules [like keyword]\n"
345 "       Shows Asterisk modules currently in use, and usage statistics.\n";
346
347 static char uptime_help[] =
348 "Usage: core show uptime [seconds]\n"
349 "       Shows Asterisk uptime information.\n"
350 "       The seconds word returns the uptime in seconds only.\n";
351
352 static void print_uptimestr(int fd, time_t timeval, const char *prefix, int printsec)
353 {
354         int x; /* the main part - years, weeks, etc. */
355         char timestr[256]="", *s = timestr;
356         size_t maxbytes = sizeof(timestr);
357
358 #define SECOND (1)
359 #define MINUTE (SECOND*60)
360 #define HOUR (MINUTE*60)
361 #define DAY (HOUR*24)
362 #define WEEK (DAY*7)
363 #define YEAR (DAY*365)
364 #define ESS(x) ((x == 1) ? "" : "s")    /* plural suffix */
365 #define NEEDCOMMA(x) ((x)? ",": "")     /* define if we need a comma */
366         if (timeval < 0)        /* invalid, nothing to show */
367                 return;
368         if (printsec)  {        /* plain seconds output */
369                 ast_build_string(&s, &maxbytes, "%lu", (u_long)timeval);
370                 timeval = 0; /* bypass the other cases */
371         }
372         if (timeval > YEAR) {
373                 x = (timeval / YEAR);
374                 timeval -= (x * YEAR);
375                 ast_build_string(&s, &maxbytes, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval));
376         }
377         if (timeval > WEEK) {
378                 x = (timeval / WEEK);
379                 timeval -= (x * WEEK);
380                 ast_build_string(&s, &maxbytes, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval));
381         }
382         if (timeval > DAY) {
383                 x = (timeval / DAY);
384                 timeval -= (x * DAY);
385                 ast_build_string(&s, &maxbytes, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval));
386         }
387         if (timeval > HOUR) {
388                 x = (timeval / HOUR);
389                 timeval -= (x * HOUR);
390                 ast_build_string(&s, &maxbytes, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval));
391         }
392         if (timeval > MINUTE) {
393                 x = (timeval / MINUTE);
394                 timeval -= (x * MINUTE);
395                 ast_build_string(&s, &maxbytes, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval));
396         }
397         x = timeval;
398         if (x > 0)
399                 ast_build_string(&s, &maxbytes, "%d second%s ", x, ESS(x));
400         if (timestr[0] != '\0')
401                 ast_cli(fd, "%s: %s\n", prefix, timestr);
402 }
403
404 static int handle_showuptime(int fd, int argc, char *argv[])
405 {
406         /* 'show uptime [seconds]' */
407         time_t curtime = time(NULL);
408         int printsec = (argc == 4 && !strcasecmp(argv[3],"seconds"));
409
410         if (argc != 3 && !printsec)
411                 return RESULT_SHOWUSAGE;
412         if (ast_startuptime)
413                 print_uptimestr(fd, curtime - ast_startuptime, "System uptime", printsec);
414         if (ast_lastreloadtime)
415                 print_uptimestr(fd, curtime - ast_lastreloadtime, "Last reload", printsec);
416         return RESULT_SUCCESS;
417 }
418
419 /* core show modules [like keyword] */
420 static int handle_modlist(int fd, int argc, char *argv[])
421 {
422         char *like = "";
423         if (argc != 3 && argc != 5)
424                 return RESULT_SHOWUSAGE;
425         else if (argc == 5) {
426                 if (strcmp(argv[3],"like")) 
427                         return RESULT_SHOWUSAGE;
428                 like = argv[4];
429         }
430                 
431         ast_mutex_lock(&climodentrylock);
432         climodentryfd = fd; /* global, protected by climodentrylock */
433         ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
434         ast_cli(fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
435         climodentryfd = -1;
436         ast_mutex_unlock(&climodentrylock);
437         return RESULT_SUCCESS;
438 }
439 #undef MODLIST_FORMAT
440 #undef MODLIST_FORMAT2
441
442 /* core show channels [concise|verbose] */
443 static int handle_chanlist(int fd, int argc, char *argv[])
444 {
445 #define FORMAT_STRING  "%-20.20s %-20.20s %-7.7s %-30.30s\n"
446 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
447 #define CONCISE_FORMAT_STRING  "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s\n"
448 #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"
449 #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"
450
451         struct ast_channel *c = NULL;
452         char durbuf[10] = "-";
453         char locbuf[40];
454         char appdata[40];
455         int duration;
456         int durh, durm, durs;
457         int numchans = 0, concise = 0, verbose = 0;
458
459         if (argc == 4) {
460                 concise = !strcasecmp(argv[2],"concise");
461                 verbose = !strcasecmp(argv[2],"verbose");
462         }
463
464         if (argc < 3 || argc > 4 || (argc == 4 && !concise && !verbose))
465                 return RESULT_SHOWUSAGE;
466
467         if (!concise && !verbose)
468                 ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
469         else if (verbose)
470                 ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data", 
471                         "CallerID", "Duration", "Accountcode", "BridgedTo");
472
473         while ((c = ast_channel_walk_locked(c)) != NULL) {
474                 struct ast_channel *bc = ast_bridged_channel(c);
475                 if ((concise || verbose)  && c->cdr && !ast_tvzero(c->cdr->start)) {
476                         duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
477                         if (verbose) {
478                                 durh = duration / 3600;
479                                 durm = (duration % 3600) / 60;
480                                 durs = duration % 60;
481                                 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
482                         } else {
483                                 snprintf(durbuf, sizeof(durbuf), "%d", duration);
484                         }                               
485                 } else {
486                         durbuf[0] = '\0';
487                 }
488                 if (concise) {
489                         ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
490                                 c->appl ? c->appl : "(None)",
491                                 S_OR(c->data, ""),      /* XXX different from verbose ? */
492                                 S_OR(c->cid.cid_num, ""),
493                                 S_OR(c->accountcode, ""),
494                                 c->amaflags, 
495                                 durbuf,
496                                 bc ? bc->name : "(None)");
497                 } else if (verbose) {
498                         ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
499                                 c->appl ? c->appl : "(None)",
500                                 c->data ? S_OR(c->data, "(Empty)" ): "(None)",
501                                 S_OR(c->cid.cid_num, ""),
502                                 durbuf,
503                                 S_OR(c->accountcode, ""),
504                                 bc ? bc->name : "(None)");
505                 } else {
506                         if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten)) 
507                                 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
508                         else
509                                 strcpy(locbuf, "(None)");
510                         if (c->appl)
511                                 snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, c->data ? c->data : "");
512                         else
513                                 strcpy(appdata, "(None)");
514                         ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
515                 }
516                 numchans++;
517                 ast_channel_unlock(c);
518         }
519         if (!concise) {
520                 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
521                 if (option_maxcalls)
522                         ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
523                                 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
524                                 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
525                 else
526                         ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
527         }
528         return RESULT_SUCCESS;
529         
530 #undef FORMAT_STRING
531 #undef FORMAT_STRING2
532 #undef CONCISE_FORMAT_STRING
533 #undef VERBOSE_FORMAT_STRING
534 #undef VERBOSE_FORMAT_STRING2
535 }
536
537 static char showchan_help[] = 
538 "Usage: channel show <channel>\n"
539 "       Shows lots of information about the specified channel.\n";
540
541 static char debugchan_help[] = 
542 "Usage: channel debug <channel>\n"
543 "       Enables debugging on a specific channel.\n";
544
545 static char nodebugchan_help[] = 
546 "Usage: channel nodebug <channel>\n"
547 "       Disables debugging on a specific channel.\n";
548
549 static char commandcomplete_help[] = 
550 "Usage: _command complete \"<line>\" text state\n"
551 "       This function is used internally to help with command completion and should.\n"
552 "       never be called by the user directly.\n";
553
554 static char commandnummatches_help[] = 
555 "Usage: _command nummatches \"<line>\" text \n"
556 "       This function is used internally to help with command completion and should.\n"
557 "       never be called by the user directly.\n";
558
559 static char commandmatchesarray_help[] = 
560 "Usage: _command matchesarray \"<line>\" text \n"
561 "       This function is used internally to help with command completion and should.\n"
562 "       never be called by the user directly.\n";
563
564 static int handle_softhangup(int fd, int argc, char *argv[])
565 {
566         struct ast_channel *c=NULL;
567         if (argc != 3)
568                 return RESULT_SHOWUSAGE;
569         c = ast_get_channel_by_name_locked(argv[2]);
570         if (c) {
571                 ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
572                 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
573                 ast_channel_unlock(c);
574         } else
575                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
576         return RESULT_SUCCESS;
577 }
578
579 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
580
581 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
582 {
583         char *buf, *obuf;
584         int buflen = 2048;
585         int len = 0;
586         char **matches;
587         int x, matchlen;
588
589         if (argc != 4)
590                 return RESULT_SHOWUSAGE;
591         if (!(buf = ast_malloc(buflen)))
592                 return RESULT_FAILURE;
593         buf[len] = '\0';
594         matches = ast_cli_completion_matches(argv[2], argv[3]);
595         if (matches) {
596                 for (x=0; matches[x]; x++) {
597                         matchlen = strlen(matches[x]) + 1;
598                         if (len + matchlen >= buflen) {
599                                 buflen += matchlen * 3;
600                                 obuf = buf;
601                                 if (!(buf = ast_realloc(obuf, buflen))) 
602                                         /* Memory allocation failure...  Just free old buffer and be done */
603                                         free(obuf);
604                         }
605                         if (buf)
606                                 len += sprintf( buf + len, "%s ", matches[x]);
607                         free(matches[x]);
608                         matches[x] = NULL;
609                 }
610                 free(matches);
611         }
612
613         if (buf) {
614                 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
615                 free(buf);
616         } else
617                 ast_cli(fd, "NULL\n");
618
619         return RESULT_SUCCESS;
620 }
621
622
623
624 static int handle_commandnummatches(int fd, int argc, char *argv[])
625 {
626         int matches = 0;
627
628         if (argc != 4)
629                 return RESULT_SHOWUSAGE;
630
631         matches = ast_cli_generatornummatches(argv[2], argv[3]);
632
633         ast_cli(fd, "%d", matches);
634
635         return RESULT_SUCCESS;
636 }
637
638 static int handle_commandcomplete(int fd, int argc, char *argv[])
639 {
640         char *buf;
641
642         if (argc != 5)
643                 return RESULT_SHOWUSAGE;
644         buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
645         if (buf) {
646                 ast_cli(fd, buf);
647                 free(buf);
648         } else
649                 ast_cli(fd, "NULL\n");
650         return RESULT_SUCCESS;
651 }
652
653 /* XXX todo: merge next two functions!!! */
654 static int handle_debugchan(int fd, int argc, char *argv[])
655 {
656         struct ast_channel *c=NULL;
657         int is_all;
658
659         /* 'debug channel {all|chan_id}' */
660         if (argc != 4)
661                 return RESULT_SHOWUSAGE;
662
663         is_all = !strcasecmp("all", argv[3]);
664         if (is_all) {
665                 global_fin |= DEBUGCHAN_FLAG;
666                 global_fout |= DEBUGCHAN_FLAG;
667                 c = ast_channel_walk_locked(NULL);
668         } else {
669                 c = ast_get_channel_by_name_locked(argv[3]);
670                 if (c == NULL)
671                         ast_cli(fd, "No such channel %s\n", argv[3]);
672         }
673         while (c) {
674                 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
675                         c->fin |= DEBUGCHAN_FLAG;
676                         c->fout |= DEBUGCHAN_FLAG;
677                         ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
678                 }
679                 ast_channel_unlock(c);
680                 if (!is_all)
681                         break;
682                 c = ast_channel_walk_locked(c);
683         }
684         ast_cli(fd, "Debugging on new channels is enabled\n");
685         return RESULT_SUCCESS;
686 }
687
688 static int handle_nodebugchan(int fd, int argc, char *argv[])
689 {
690         struct ast_channel *c=NULL;
691         int is_all;
692         /* 'no debug channel {all|chan_id}' */
693         if (argc != 3)
694                 return RESULT_SHOWUSAGE;
695         is_all = !strcasecmp("all", argv[2]);
696         if (is_all) {
697                 global_fin &= ~DEBUGCHAN_FLAG;
698                 global_fout &= ~DEBUGCHAN_FLAG;
699                 c = ast_channel_walk_locked(NULL);
700         } else {
701                 c = ast_get_channel_by_name_locked(argv[2]);
702                 if (c == NULL)
703                         ast_cli(fd, "No such channel %s\n", argv[2]);
704         }
705         while(c) {
706                 if ((c->fin & DEBUGCHAN_FLAG) || (c->fout & DEBUGCHAN_FLAG)) {
707                         c->fin &= ~DEBUGCHAN_FLAG;
708                         c->fout &= ~DEBUGCHAN_FLAG;
709                         ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
710                 }
711                 ast_channel_unlock(c);
712                 if (!is_all)
713                         break;
714                 c = ast_channel_walk_locked(c);
715         }
716         ast_cli(fd, "Debugging on new channels is disabled\n");
717         return RESULT_SUCCESS;
718 }
719                 
720 static int handle_showchan(int fd, int argc, char *argv[])
721 {
722         struct ast_channel *c=NULL;
723         struct timeval now;
724         char buf[2048];
725         char cdrtime[256];
726         char nf[256], wf[256], rf[256];
727         long elapsed_seconds=0;
728         int hour=0, min=0, sec=0;
729         
730         if (argc != 4)
731                 return RESULT_SHOWUSAGE;
732         now = ast_tvnow();
733         c = ast_get_channel_by_name_locked(argv[3]);
734         if (!c) {
735                 ast_cli(fd, "%s is not a known channel\n", argv[3]);
736                 return RESULT_SUCCESS;
737         }
738         if(c->cdr) {
739                 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
740                 hour = elapsed_seconds / 3600;
741                 min = (elapsed_seconds % 3600) / 60;
742                 sec = elapsed_seconds % 60;
743                 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
744         } else
745                 strcpy(cdrtime, "N/A");
746         ast_cli(fd, 
747                 " -- General --\n"
748                 "           Name: %s\n"
749                 "           Type: %s\n"
750                 "       UniqueID: %s\n"
751                 "      Caller ID: %s\n"
752                 " Caller ID Name: %s\n"
753                 "    DNID Digits: %s\n"
754                 "          State: %s (%d)\n"
755                 "          Rings: %d\n"
756                 "  NativeFormats: %s\n"
757                 "    WriteFormat: %s\n"
758                 "     ReadFormat: %s\n"
759                 " WriteTranscode: %s\n"
760                 "  ReadTranscode: %s\n"
761                 "1st File Descriptor: %d\n"
762                 "      Frames in: %d%s\n"
763                 "     Frames out: %d%s\n"
764                 " Time to Hangup: %ld\n"
765                 "   Elapsed Time: %s\n"
766                 "  Direct Bridge: %s\n"
767                 "Indirect Bridge: %s\n"
768                 " --   PBX   --\n"
769                 "        Context: %s\n"
770                 "      Extension: %s\n"
771                 "       Priority: %d\n"
772                 "     Call Group: %llu\n"
773                 "   Pickup Group: %llu\n"
774                 "    Application: %s\n"
775                 "           Data: %s\n"
776                 "    Blocking in: %s\n",
777                 c->name, c->tech->type, c->uniqueid,
778                 S_OR(c->cid.cid_num, "(N/A)"),
779                 S_OR(c->cid.cid_name, "(N/A)"),
780                 S_OR(c->cid.cid_dnid, "(N/A)"), ast_state2str(c->_state), c->_state, c->rings, 
781                 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats), 
782                 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat), 
783                 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
784                 c->writetrans ? "Yes" : "No",
785                 c->readtrans ? "Yes" : "No",
786                 c->fds[0],
787                 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
788                 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
789                 (long)c->whentohangup,
790                 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>", 
791                 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
792                 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
793                 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
794         
795         if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
796                 ast_cli(fd,"      Variables:\n%s\n",buf);
797         if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
798                 ast_cli(fd,"  CDR Variables:\n%s\n",buf);
799         
800         ast_channel_unlock(c);
801         return RESULT_SUCCESS;
802 }
803
804 /*
805  * helper function to generate CLI matches from a fixed set of values.
806  * A NULL word is acceptable.
807  */
808 char *ast_cli_complete(const char *word, char *const choices[], int state)
809 {
810         int i, which = 0, len;
811         len = ast_strlen_zero(word) ? 0 : strlen(word);
812
813         for (i = 0; choices[i]; i++) {
814                 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
815                         return ast_strdup(choices[i]);
816         }
817         return NULL;
818 }
819
820 static char *complete_show_channels(const char *line, const char *word, int pos, int state)
821 {
822         static char *choices[] = { "concise", "verbose", NULL };
823
824         return (pos != 3) ? NULL : ast_cli_complete(word, choices, state);
825 }
826
827 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
828 {
829         struct ast_channel *c = NULL;
830         int which = 0;
831         int wordlen;
832         char notfound = '\0';
833         char *ret = &notfound; /* so NULL can break the loop */
834
835         if (pos != rpos)
836                 return NULL;
837
838         wordlen = strlen(word); 
839
840         while (ret == &notfound && (c = ast_channel_walk_locked(c))) {
841                 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
842                         ret = ast_strdup(c->name);
843                 ast_channel_unlock(c);
844         }
845         return ret == &notfound ? NULL : ret;
846 }
847
848 static char *complete_ch_3(const char *line, const char *word, int pos, int state)
849 {
850         return ast_complete_channels(line, word, pos, state, 2);
851 }
852
853 static char *complete_ch_4(const char *line, const char *word, int pos, int state)
854 {
855         return ast_complete_channels(line, word, pos, state, 3);
856 }
857
858 static char *complete_mod_3_nr(const char *line, const char *word, int pos, int state)
859 {
860         return ast_module_helper(line, word, pos, state, 2, 0);
861 }
862
863 static char *complete_mod_3(const char *line, const char *word, int pos, int state)
864 {
865         return ast_module_helper(line, word, pos, state, 2, 1);
866 }
867
868 static char *complete_mod_4(const char *line, const char *word, int pos, int state)
869 {
870         return ast_module_helper(line, word, pos, state, 3, 0);
871 }
872
873 static char *complete_fn(const char *line, const char *word, int pos, int state)
874 {
875         char *c;
876         char filename[256];
877
878         if (pos != 1)
879                 return NULL;
880         
881         if (word[0] == '/')
882                 ast_copy_string(filename, word, sizeof(filename));
883         else
884                 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
885         
886         c = filename_completion_function(filename, state);
887         
888         if (c && word[0] != '/')
889                 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
890         
891         return c ? strdup(c) : c;
892 }
893
894 static int group_show_channels(int fd, int argc, char *argv[])
895 {
896 #define FORMAT_STRING  "%-25s  %-20s  %-20s\n"
897
898         struct ast_channel *c = NULL;
899         int numchans = 0;
900         struct ast_var_t *current;
901         struct varshead *headp;
902         regex_t regexbuf;
903         int havepattern = 0;
904
905         if (argc < 3 || argc > 4)
906                 return RESULT_SHOWUSAGE;
907         
908         if (argc == 4) {
909                 if (regcomp(&regexbuf, argv[3], REG_EXTENDED | REG_NOSUB))
910                         return RESULT_SHOWUSAGE;
911                 havepattern = 1;
912         }
913
914         ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
915         while ( (c = ast_channel_walk_locked(c)) != NULL) {
916                 headp=&c->varshead;
917                 AST_LIST_TRAVERSE(headp,current,entries) {
918                         if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
919                                 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
920                                         ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
921                                                 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
922                                         numchans++;
923                                 }
924                         } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
925                                 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
926                                         ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
927                                         numchans++;
928                                 }
929                         }
930                 }
931                 numchans++;
932                 ast_channel_unlock(c);
933         }
934
935         if (havepattern)
936                 regfree(&regexbuf);
937
938         ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
939         return RESULT_SUCCESS;
940 #undef FORMAT_STRING
941 }
942
943 static int handle_help(int fd, int argc, char *argv[]);
944
945 static char * complete_help(const char *text, const char *word, int pos, int state)
946 {
947         /* skip first 4 or 5 chars, "help "*/
948         int l = strlen(text);
949
950         if (l > 5)
951                 l = 5;
952         text += l;
953         /* XXX watch out, should stop to the non-generator parts */
954         return __ast_cli_generator(text, word, state, 0);
955 }
956
957 /* XXX Nothing in this array can currently be deprecated...
958    You have to change the way find_cli works in order to remove this array
959    I recommend doing this eventually...
960  */
961 static struct ast_cli_entry builtins[] = {
962         /* Keep alphabetized, with longer matches first (example: abcd before abc) */
963         { { "_command", "complete", NULL },
964         handle_commandcomplete, "Command complete",
965         commandcomplete_help },
966
967         { { "_command", "nummatches", NULL },
968         handle_commandnummatches, "Returns number of command matches",
969         commandnummatches_help },
970
971         { { "_command", "matchesarray", NULL },
972         handle_commandmatchesarray, "Returns command matches array",
973         commandmatchesarray_help },
974
975         { { NULL }, NULL, NULL, NULL }
976 };
977
978 static struct ast_cli_entry cli_cli[] = {
979         { { "core", "show", "channels", NULL },
980         handle_chanlist, "Display information on channels",
981         chanlist_help, complete_show_channels },
982
983         { { "core", "show" "channel", NULL },
984         handle_showchan, "Display information on a specific channel",
985         showchan_help, complete_ch_4 },
986
987         { { "core", "debug", "channel", NULL },
988         handle_debugchan, "Enable debugging on a channel",
989         debugchan_help, complete_ch_3 },
990
991         { { "core", "no", "debug", "channel", NULL },
992         handle_nodebugchan, "Disable debugging on a channel",
993         nodebugchan_help, complete_ch_3 },
994
995         { { "core", "set", "debug", NULL },
996         handle_debug, "Set level of debug chattiness",
997         debug_help },
998
999         { { "core", "set", "no", "debug", NULL },
1000         handle_nodebug, "Turns off debug chattiness",
1001         nodebug_help },
1002
1003         { { "core", "set", "verbose", NULL },
1004         handle_verbose, "Set level of verboseness",
1005         verbose_help },
1006
1007         { { "group", "show", "channels", NULL },
1008         group_show_channels, "Display active channels with group(s)",
1009         group_show_channels_help },
1010
1011         { { "help", NULL },
1012         handle_help, "Display help list, or specific help on a command",
1013         help_help, complete_help },
1014
1015         { { "logger", "mute", NULL },
1016         handle_logger_mute, "Toggle logging output to a console",
1017         logger_mute_help },
1018
1019         { { "core", "show", "modules", NULL },
1020         handle_modlist, "List modules and info",
1021         modlist_help },
1022
1023         { { "core", "show", "modules", "like", NULL },
1024         handle_modlist, "List modules and info",
1025         modlist_help, complete_mod_4 },
1026
1027         { { "load", NULL },
1028         handle_load, "Load a module by name",
1029         load_help, complete_fn },
1030
1031         { { "reload", NULL },
1032         handle_reload, "Reload configuration",
1033         reload_help, complete_mod_3 },
1034
1035         { { "unload", NULL },
1036         handle_unload, "Unload a module by name",
1037         unload_help, complete_mod_3_nr },
1038
1039         { { "core", "show", "uptime", NULL },
1040         handle_showuptime, "Show uptime information",
1041         uptime_help },
1042
1043         { { "soft", "hangup", NULL },
1044         handle_softhangup, "Request a hangup on a given channel",
1045         softhangup_help, complete_ch_3 },
1046 };
1047
1048 /*! \brief initialize the _full_cmd string in * each of the builtins. */
1049 void ast_builtins_init(void)
1050 {
1051         struct ast_cli_entry *e;
1052
1053         for (e = builtins; e->cmda[0] != NULL; e++) {
1054                 char buf[80];
1055                 ast_join(buf, sizeof(buf), e->cmda);
1056                 e->_full_cmd = strdup(buf);
1057                 if (!e->_full_cmd)
1058                         ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
1059         }
1060
1061         ast_cli_register_multiple(cli_cli, sizeof(cli_cli) / sizeof(struct ast_cli_entry));
1062 }
1063
1064 /*
1065  * We have two sets of commands: builtins are stored in a
1066  * NULL-terminated array of ast_cli_entry, whereas external
1067  * commands are in a list.
1068  * When navigating, we need to keep two pointers and get
1069  * the next one in lexicographic order. For the purpose,
1070  * we use a structure.
1071  */
1072
1073 struct cli_iterator {
1074         struct ast_cli_entry *builtins;
1075         struct ast_cli_entry *helpers;
1076 };
1077
1078 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
1079 {
1080         struct ast_cli_entry *e;
1081
1082         if (i->builtins == NULL && i->helpers == NULL) {
1083                 /* initialize */
1084                 i->builtins = builtins;
1085                 i->helpers = AST_LIST_FIRST(&helpers);
1086         }
1087         e = i->builtins; /* temporary */
1088         if (!e->cmda[0] || (i->helpers &&
1089                     strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
1090                 /* Use helpers */
1091                 e = i->helpers;
1092                 if (e)
1093                         i->helpers = AST_LIST_NEXT(e, list);
1094         } else { /* use builtin. e is already set  */
1095                 (i->builtins)++;        /* move to next */
1096         }
1097         return e;
1098 }
1099
1100 /*!
1101  * \brief locate a cli command in the 'helpers' list (which must be locked).
1102  * exact has 3 values:
1103  *      0       returns if the search key is equal or longer than the entry.
1104  *      -1      true if the mismatch is on the last word XXX not true!
1105  *      1       true only on complete, exact match.
1106  */
1107 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1108 {
1109         int matchlen = -1;      /* length of longest match so far */
1110         struct ast_cli_entry *cand = NULL, *e=NULL;
1111         struct cli_iterator i = { NULL, NULL};
1112
1113         while( (e = cli_next(&i)) ) {
1114                 int y;
1115                 for (y = 0 ; cmds[y] && e->cmda[y]; y++) {
1116                         if (strcasecmp(e->cmda[y], cmds[y]))
1117                                 break;
1118                 }
1119                 if (e->cmda[y] == NULL) {       /* no more words in candidate */
1120                         if (cmds[y] == NULL)    /* this is an exact match, cannot do better */
1121                                 break;
1122                         /* here the search key is longer than the candidate */
1123                         if (match_type != 0)    /* but we look for almost exact match... */
1124                                 continue;       /* so we skip this one. */
1125                         /* otherwise we like it (case 0) */
1126                 } else {                        /* still words in candidate */
1127                         if (cmds[y] == NULL)    /* search key is shorter, not good */
1128                                 continue;
1129                         /* if we get here, both words exist but there is a mismatch */
1130                         if (match_type == 0)    /* not the one we look for */
1131                                 continue;
1132                         if (match_type == 1)    /* not the one we look for */
1133                                 continue;
1134                         if (cmds[y+1] != NULL || e->cmda[y+1] != NULL)  /* not the one we look for */
1135                                 continue;
1136                         /* we are in case match_type == -1 and mismatch on last word */
1137                 }
1138                 if (cand == NULL || y > matchlen)       /* remember the candidate */
1139                         cand = e;
1140         }
1141         return e ? e : cand;
1142 }
1143
1144 static char *find_best(char *argv[])
1145 {
1146         static char cmdline[80];
1147         int x;
1148         /* See how close we get, then print the candidate */
1149         char *myargv[AST_MAX_CMD_LEN];
1150         for (x=0;x<AST_MAX_CMD_LEN;x++)
1151                 myargv[x]=NULL;
1152         AST_LIST_LOCK(&helpers);
1153         for (x=0;argv[x];x++) {
1154                 myargv[x] = argv[x];
1155                 if (!find_cli(myargv, -1))
1156                         break;
1157         }
1158         AST_LIST_UNLOCK(&helpers);
1159         ast_join(cmdline, sizeof(cmdline), myargv);
1160         return cmdline;
1161 }
1162
1163 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1164 {
1165         if (e->deprecate_cmd) {
1166                 __ast_cli_unregister(e->deprecate_cmd, e);
1167         }
1168         if (e->inuse) {
1169                 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1170         } else {
1171                 AST_LIST_LOCK(&helpers);
1172                 AST_LIST_REMOVE(&helpers, e, list);
1173                 AST_LIST_UNLOCK(&helpers);
1174         }
1175         return 0;
1176 }
1177
1178 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1179 {
1180         struct ast_cli_entry *cur;
1181         char fulle[80] ="";
1182         int lf, ret = -1;
1183         
1184         ast_join(fulle, sizeof(fulle), e->cmda);
1185         AST_LIST_LOCK(&helpers);
1186         
1187         if (find_cli(e->cmda, 1)) {
1188                 AST_LIST_UNLOCK(&helpers);
1189                 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1190                 goto done;
1191         }
1192         e->_full_cmd = ast_strdup(fulle);
1193         if (!e->_full_cmd)
1194                 goto done;
1195
1196         if (ed) {
1197                 e->deprecated = 1;
1198                 e->summary = ed->summary;
1199                 e->usage = ed->usage;
1200                 /* XXX If command A deprecates command B, and command B deprecates command C...
1201                    Do we want to show command A or command B when telling the user to use new syntax?
1202                    This currently would show command A.
1203                    To show command B, you just need to always use ed->_full_cmd.
1204                  */
1205                 e->_deprecated_by = S_OR(ed->_deprecated_by, ed->_full_cmd);
1206         } else {
1207                 e->deprecated = 0;
1208         }
1209
1210         lf = strlen(fulle);
1211         AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1212                 int len = strlen(cur->_full_cmd);
1213                 if (lf < len)
1214                         len = lf;
1215                 if (strncasecmp(fulle, cur->_full_cmd, len) < 0) {
1216                         AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list); 
1217                         break;
1218                 }
1219         }
1220         AST_LIST_TRAVERSE_SAFE_END;
1221
1222         if (!cur)
1223                 AST_LIST_INSERT_TAIL(&helpers, e, list); 
1224         ret = 0;        /* success */
1225
1226 done:
1227         AST_LIST_UNLOCK(&helpers);
1228
1229         if (e->deprecate_cmd) {
1230                 /* This command deprecates another command.  Register that one also. */
1231                 __ast_cli_register(e->deprecate_cmd, e);
1232         }
1233         
1234         return ret;
1235 }
1236
1237 /* wrapper function, so we can unregister deprecated commands recursively */
1238 int ast_cli_unregister(struct ast_cli_entry *e)
1239 {
1240         return __ast_cli_unregister(e, NULL);
1241 }
1242
1243 /* wrapper function, so we can register deprecated commands recursively */
1244 int ast_cli_register(struct ast_cli_entry *e)
1245 {
1246         return __ast_cli_register(e, NULL);
1247 }
1248
1249 /*
1250  * register/unregister an array of entries.
1251  */
1252 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1253 {
1254         int i;
1255
1256         for (i = 0; i < len; i++)
1257                 ast_cli_register(e + i);
1258 }
1259
1260 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1261 {
1262         int i;
1263
1264         for (i = 0; i < len; i++)
1265                 ast_cli_unregister(e + i);
1266 }
1267
1268
1269 /*! \brief helper for help_workhorse and final part of
1270  * handle_help. if locked = 0 it's just help_workhorse,
1271  * otherwise assume the list is already locked and print
1272  * an error message if not found.
1273  */
1274 static int help1(int fd, char *match[], int locked)
1275 {
1276         char matchstr[80] = "";
1277         struct ast_cli_entry *e;
1278         int len = 0;
1279         int found = 0;
1280         struct cli_iterator i = { NULL, NULL};
1281
1282         if (match) {
1283                 ast_join(matchstr, sizeof(matchstr), match);
1284                 len = strlen(matchstr);
1285         }
1286         if (!locked)
1287                 AST_LIST_LOCK(&helpers);
1288         while ( (e = cli_next(&i)) ) {
1289                 /* Hide commands that start with '_' */
1290                 if (e->_full_cmd[0] == '_')
1291                         continue;
1292                 /* Hide commands that are marked as deprecated. */
1293                 if (e->deprecated)
1294                         continue;
1295                 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1296                         continue;
1297                 ast_cli(fd, "%25.25s  %s\n", e->_full_cmd, e->summary);
1298                 found++;
1299         }
1300         AST_LIST_UNLOCK(&helpers);
1301         if (!locked && !found && matchstr[0])
1302                 ast_cli(fd, "No such command '%s'.\n", matchstr);
1303         return 0;
1304 }
1305
1306 static int help_workhorse(int fd, char *match[])
1307 {
1308         return help1(fd, match, 0 /* do not print errors */);
1309 }
1310
1311 static int handle_help(int fd, int argc, char *argv[])
1312 {
1313         char fullcmd[80];
1314         struct ast_cli_entry *e;
1315
1316         if (argc < 1)
1317                 return RESULT_SHOWUSAGE;
1318         if (argc == 1)
1319                 return help_workhorse(fd, NULL);
1320
1321         AST_LIST_LOCK(&helpers);
1322         e = find_cli(argv + 1, 1);      /* try exact match first */
1323         if (!e)
1324                 return help1(fd, argv + 1, 1 /* locked */);
1325         if (e->usage)
1326                 ast_cli(fd, "%s", e->usage);
1327         else {
1328                 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1329                 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1330         }
1331         AST_LIST_UNLOCK(&helpers);
1332         return RESULT_SUCCESS;
1333 }
1334
1335 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1336 {
1337         char *dup, *cur;
1338         int x = 0;
1339         int quoted = 0;
1340         int escaped = 0;
1341         int whitespace = 1;
1342
1343         *trailingwhitespace = 0;
1344         if (s == NULL)  /* invalid, though! */
1345                 return NULL;
1346         /* make a copy to store the parsed string */
1347         if (!(dup = ast_strdup(s)))
1348                 return NULL;
1349
1350         cur = dup;
1351         /* scan the original string copying into cur when needed */
1352         for (; *s ; s++) {
1353                 if (x >= max - 1) {
1354                         ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1355                         break;
1356                 }
1357                 if (*s == '"' && !escaped) {
1358                         quoted = !quoted;
1359                         if (quoted && whitespace) {
1360                                 /* start a quoted string from previous whitespace: new argument */
1361                                 argv[x++] = cur;
1362                                 whitespace = 0;
1363                         }
1364                 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1365                         /* If we are not already in whitespace, and not in a quoted string or
1366                            processing an escape sequence, and just entered whitespace, then
1367                            finalize the previous argument and remember that we are in whitespace
1368                         */
1369                         if (!whitespace) {
1370                                 *cur++ = '\0';
1371                                 whitespace = 1;
1372                         }
1373                 } else if (*s == '\\' && !escaped) {
1374                         escaped = 1;
1375                 } else {
1376                         if (whitespace) {
1377                                 /* we leave whitespace, and are not quoted. So it's a new argument */
1378                                 argv[x++] = cur;
1379                                 whitespace = 0;
1380                         }
1381                         *cur++ = *s;
1382                         escaped = 0;
1383                 }
1384         }
1385         /* Null terminate */
1386         *cur++ = '\0';
1387         /* XXX put a NULL in the last argument, because some functions that take
1388          * the array may want a null-terminated array.
1389          * argc still reflects the number of non-NULL entries.
1390          */
1391         argv[x] = NULL;
1392         *argc = x;
1393         *trailingwhitespace = whitespace;
1394         return dup;
1395 }
1396
1397 /*! \brief Return the number of unique matches for the generator */
1398 int ast_cli_generatornummatches(const char *text, const char *word)
1399 {
1400         int matches = 0, i = 0;
1401         char *buf = NULL, *oldbuf = NULL;
1402
1403         while ((buf = ast_cli_generator(text, word, i++))) {
1404                 if (!oldbuf || strcmp(buf,oldbuf))
1405                         matches++;
1406                 if (oldbuf)
1407                         free(oldbuf);
1408                 oldbuf = buf;
1409         }
1410         if (oldbuf)
1411                 free(oldbuf);
1412         return matches;
1413 }
1414
1415 char **ast_cli_completion_matches(const char *text, const char *word)
1416 {
1417         char **match_list = NULL, *retstr, *prevstr;
1418         size_t match_list_len, max_equal, which, i;
1419         int matches = 0;
1420
1421         /* leave entry 0 free for the longest common substring */
1422         match_list_len = 1;
1423         while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1424                 if (matches + 1 >= match_list_len) {
1425                         match_list_len <<= 1;
1426                         if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1427                                 return NULL;
1428                 }
1429                 match_list[++matches] = retstr;
1430         }
1431
1432         if (!match_list)
1433                 return match_list; /* NULL */
1434
1435         /* Find the longest substring that is common to all results
1436          * (it is a candidate for completion), and store a copy in entry 0.
1437          */
1438         prevstr = match_list[1];
1439         max_equal = strlen(prevstr);
1440         for (which = 2; which <= matches; which++) {
1441                 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1442                         continue;
1443                 max_equal = i;
1444         }
1445
1446         if (!(retstr = ast_malloc(max_equal + 1)))
1447                 return NULL;
1448         
1449         ast_copy_string(retstr, match_list[1], max_equal + 1);
1450         match_list[0] = retstr;
1451
1452         /* ensure that the array is NULL terminated */
1453         if (matches + 1 >= match_list_len) {
1454                 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1455                         return NULL;
1456         }
1457         match_list[matches + 1] = NULL;
1458
1459         return match_list;
1460 }
1461
1462 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1463 {
1464         char *argv[AST_MAX_ARGS];
1465         struct ast_cli_entry *e;
1466         struct cli_iterator i = { NULL, NULL };
1467         int x = 0, argindex, matchlen;
1468         int matchnum=0;
1469         char *ret = NULL;
1470         char matchstr[80] = "";
1471         int tws = 0;
1472         char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1473
1474         if (!dup)       /* error */
1475                 return NULL;
1476         argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1477         /* rebuild the command, ignore tws */
1478         ast_join(matchstr, sizeof(matchstr)-1, argv);
1479         matchlen = strlen(matchstr);
1480         if (tws) {
1481                 strcat(matchstr, " "); /* XXX */
1482                 if (matchlen)
1483                         matchlen++;
1484         }
1485         if (lock)
1486                 AST_LIST_LOCK(&helpers);
1487         while( !ret && (e = cli_next(&i)) ) {
1488                 int lc = strlen(e->_full_cmd);
1489                 if (e->_full_cmd[0] != '_' && lc > 0 && matchlen <= lc &&
1490                                 !strncasecmp(matchstr, e->_full_cmd, matchlen)) {
1491                         /* Found initial part, return a copy of the next word... */
1492                         if (e->cmda[argindex] && ++matchnum > state)
1493                                 ret = strdup(e->cmda[argindex]); /* we need a malloced string */
1494                 } else if (e->generator && !strncasecmp(matchstr, e->_full_cmd, lc) && matchstr[lc] < 33) {
1495                         /* We have a command in its entirity within us -- theoretically only one
1496                            command can have this occur */
1497                         ret = e->generator(matchstr, word, argindex, state);
1498                 }
1499         }
1500         if (lock)
1501                 AST_LIST_UNLOCK(&helpers);
1502         free(dup);
1503         return ret;
1504 }
1505
1506 char *ast_cli_generator(const char *text, const char *word, int state)
1507 {
1508         return __ast_cli_generator(text, word, state, 1);
1509 }
1510
1511 int ast_cli_command(int fd, const char *s)
1512 {
1513         char *argv[AST_MAX_ARGS];
1514         struct ast_cli_entry *e;
1515         int x;
1516         char *dup;
1517         int tws;
1518         
1519         if (!(dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws)))
1520                 return -1;
1521
1522         /* We need at least one entry, or ignore */
1523         if (x > 0) {
1524                 AST_LIST_LOCK(&helpers);
1525                 e = find_cli(argv, 0);
1526                 if (e)
1527                         e->inuse++;
1528                 AST_LIST_UNLOCK(&helpers);
1529                 if (e) {
1530                         switch(e->handler(fd, x, argv)) {
1531                         case RESULT_SHOWUSAGE:
1532                                 if (e->usage)
1533                                         ast_cli(fd, "%s", e->usage);
1534                                 else
1535                                         ast_cli(fd, "Invalid usage, but no usage information available.\n");
1536                                 break;
1537                         default:
1538                                 AST_LIST_LOCK(&helpers);
1539                                 if (e->deprecated == 1) {
1540                                         ast_cli(fd, "The '%s' command is deprecated and will be removed in a future release. Please use '%s' instead.\n", e->_full_cmd, e->_deprecated_by);
1541                                         e->deprecated = 2;
1542                                 }
1543                                 AST_LIST_UNLOCK(&helpers);
1544                                 break;
1545                         }
1546                 } else 
1547                         ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1548                 if (e)
1549                         ast_atomic_fetchadd_int(&e->inuse, -1);
1550         }
1551         free(dup);
1552         
1553         return 0;
1554 }