Merged revisions 47377 via svnmerge from
[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_ch_5(const char *line, const char *word, int pos, int state)
859 {
860         return ast_complete_channels(line, word, pos, state, 4);
861 }
862
863 static char *complete_mod_3_nr(const char *line, const char *word, int pos, int state)
864 {
865         return ast_module_helper(line, word, pos, state, 2, 0);
866 }
867
868 static char *complete_mod_3(const char *line, const char *word, int pos, int state)
869 {
870         return ast_module_helper(line, word, pos, state, 2, 1);
871 }
872
873 static char *complete_mod_4(const char *line, const char *word, int pos, int state)
874 {
875         return ast_module_helper(line, word, pos, state, 3, 0);
876 }
877
878 static char *complete_fn(const char *line, const char *word, int pos, int state)
879 {
880         char *c;
881         char filename[256];
882
883         if (pos != 1)
884                 return NULL;
885         
886         if (word[0] == '/')
887                 ast_copy_string(filename, word, sizeof(filename));
888         else
889                 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
890         
891         c = filename_completion_function(filename, state);
892         
893         if (c && word[0] != '/')
894                 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
895         
896         return c ? strdup(c) : c;
897 }
898
899 static int group_show_channels(int fd, int argc, char *argv[])
900 {
901 #define FORMAT_STRING  "%-25s  %-20s  %-20s\n"
902
903         struct ast_channel *c = NULL;
904         int numchans = 0;
905         struct ast_var_t *current;
906         struct varshead *headp;
907         regex_t regexbuf;
908         int havepattern = 0;
909
910         if (argc < 3 || argc > 4)
911                 return RESULT_SHOWUSAGE;
912         
913         if (argc == 4) {
914                 if (regcomp(&regexbuf, argv[3], REG_EXTENDED | REG_NOSUB))
915                         return RESULT_SHOWUSAGE;
916                 havepattern = 1;
917         }
918
919         ast_cli(fd, FORMAT_STRING, "Channel", "Group", "Category");
920         while ( (c = ast_channel_walk_locked(c)) != NULL) {
921                 headp=&c->varshead;
922                 AST_LIST_TRAVERSE(headp,current,entries) {
923                         if (!strncmp(ast_var_name(current), GROUP_CATEGORY_PREFIX "_", strlen(GROUP_CATEGORY_PREFIX) + 1)) {
924                                 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
925                                         ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current),
926                                                 (ast_var_name(current) + strlen(GROUP_CATEGORY_PREFIX) + 1));
927                                         numchans++;
928                                 }
929                         } else if (!strcmp(ast_var_name(current), GROUP_CATEGORY_PREFIX)) {
930                                 if (!havepattern || !regexec(&regexbuf, ast_var_value(current), 0, NULL, 0)) {
931                                         ast_cli(fd, FORMAT_STRING, c->name, ast_var_value(current), "(default)");
932                                         numchans++;
933                                 }
934                         }
935                 }
936                 numchans++;
937                 ast_channel_unlock(c);
938         }
939
940         if (havepattern)
941                 regfree(&regexbuf);
942
943         ast_cli(fd, "%d active channel%s\n", numchans, (numchans != 1) ? "s" : "");
944         return RESULT_SUCCESS;
945 #undef FORMAT_STRING
946 }
947
948 static int handle_help(int fd, int argc, char *argv[]);
949
950 static char * complete_help(const char *text, const char *word, int pos, int state)
951 {
952         /* skip first 4 or 5 chars, "help "*/
953         int l = strlen(text);
954
955         if (l > 5)
956                 l = 5;
957         text += l;
958         /* XXX watch out, should stop to the non-generator parts */
959         return __ast_cli_generator(text, word, state, 0);
960 }
961
962 /* XXX Nothing in this array can currently be deprecated...
963    You have to change the way find_cli works in order to remove this array
964    I recommend doing this eventually...
965  */
966 static struct ast_cli_entry builtins[] = {
967         /* Keep alphabetized, with longer matches first (example: abcd before abc) */
968         { { "_command", "complete", NULL },
969         handle_commandcomplete, "Command complete",
970         commandcomplete_help },
971
972         { { "_command", "nummatches", NULL },
973         handle_commandnummatches, "Returns number of command matches",
974         commandnummatches_help },
975
976         { { "_command", "matchesarray", NULL },
977         handle_commandmatchesarray, "Returns command matches array",
978         commandmatchesarray_help },
979
980         { { NULL }, NULL, NULL, NULL }
981 };
982
983 static struct ast_cli_entry cli_cli[] = {
984         { { "core", "show", "channels", NULL },
985         handle_chanlist, "Display information on channels",
986         chanlist_help, complete_show_channels },
987
988         { { "core", "show" "channel", NULL },
989         handle_showchan, "Display information on a specific channel",
990         showchan_help, complete_ch_4 },
991
992         { { "core", "debug", "channel", NULL },
993         handle_debugchan, "Enable debugging on a channel",
994         debugchan_help, complete_ch_4 },
995
996         { { "core", "no", "debug", "channel", NULL },
997         handle_nodebugchan, "Disable debugging on a channel",
998         nodebugchan_help, complete_ch_5 },
999
1000         { { "core", "set", "debug", NULL },
1001         handle_debug, "Set level of debug chattiness",
1002         debug_help },
1003
1004         { { "core", "set", "no", "debug", NULL },
1005         handle_nodebug, "Turns off debug chattiness",
1006         nodebug_help },
1007
1008         { { "core", "set", "verbose", NULL },
1009         handle_verbose, "Set level of verboseness",
1010         verbose_help },
1011
1012         { { "group", "show", "channels", NULL },
1013         group_show_channels, "Display active channels with group(s)",
1014         group_show_channels_help },
1015
1016         { { "help", NULL },
1017         handle_help, "Display help list, or specific help on a command",
1018         help_help, complete_help },
1019
1020         { { "logger", "mute", NULL },
1021         handle_logger_mute, "Toggle logging output to a console",
1022         logger_mute_help },
1023
1024         { { "core", "show", "modules", NULL },
1025         handle_modlist, "List modules and info",
1026         modlist_help },
1027
1028         { { "core", "show", "modules", "like", NULL },
1029         handle_modlist, "List modules and info",
1030         modlist_help, complete_mod_4 },
1031
1032         { { "load", NULL },
1033         handle_load, "Load a module by name",
1034         load_help, complete_fn },
1035
1036         { { "reload", NULL },
1037         handle_reload, "Reload configuration",
1038         reload_help, complete_mod_3 },
1039
1040         { { "unload", NULL },
1041         handle_unload, "Unload a module by name",
1042         unload_help, complete_mod_3_nr },
1043
1044         { { "core", "show", "uptime", NULL },
1045         handle_showuptime, "Show uptime information",
1046         uptime_help },
1047
1048         { { "soft", "hangup", NULL },
1049         handle_softhangup, "Request a hangup on a given channel",
1050         softhangup_help, complete_ch_3 },
1051 };
1052
1053 /*! \brief initialize the _full_cmd string in * each of the builtins. */
1054 void ast_builtins_init(void)
1055 {
1056         struct ast_cli_entry *e;
1057
1058         for (e = builtins; e->cmda[0] != NULL; e++) {
1059                 char buf[80];
1060                 ast_join(buf, sizeof(buf), e->cmda);
1061                 e->_full_cmd = strdup(buf);
1062                 if (!e->_full_cmd)
1063                         ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
1064         }
1065
1066         ast_cli_register_multiple(cli_cli, sizeof(cli_cli) / sizeof(struct ast_cli_entry));
1067 }
1068
1069 /*
1070  * We have two sets of commands: builtins are stored in a
1071  * NULL-terminated array of ast_cli_entry, whereas external
1072  * commands are in a list.
1073  * When navigating, we need to keep two pointers and get
1074  * the next one in lexicographic order. For the purpose,
1075  * we use a structure.
1076  */
1077
1078 struct cli_iterator {
1079         struct ast_cli_entry *builtins;
1080         struct ast_cli_entry *helpers;
1081 };
1082
1083 static struct ast_cli_entry *cli_next(struct cli_iterator *i)
1084 {
1085         struct ast_cli_entry *e;
1086
1087         if (i->builtins == NULL && i->helpers == NULL) {
1088                 /* initialize */
1089                 i->builtins = builtins;
1090                 i->helpers = AST_LIST_FIRST(&helpers);
1091         }
1092         e = i->builtins; /* temporary */
1093         if (!e->cmda[0] || (i->helpers &&
1094                     strcmp(i->helpers->_full_cmd, e->_full_cmd) < 0)) {
1095                 /* Use helpers */
1096                 e = i->helpers;
1097                 if (e)
1098                         i->helpers = AST_LIST_NEXT(e, list);
1099         } else { /* use builtin. e is already set  */
1100                 (i->builtins)++;        /* move to next */
1101         }
1102         return e;
1103 }
1104
1105 /*!
1106  * \brief locate a cli command in the 'helpers' list (which must be locked).
1107  * exact has 3 values:
1108  *      0       returns if the search key is equal or longer than the entry.
1109  *      -1      true if the mismatch is on the last word XXX not true!
1110  *      1       true only on complete, exact match.
1111  */
1112 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1113 {
1114         int matchlen = -1;      /* length of longest match so far */
1115         struct ast_cli_entry *cand = NULL, *e=NULL;
1116         struct cli_iterator i = { NULL, NULL};
1117
1118         while( (e = cli_next(&i)) ) {
1119                 int y;
1120                 for (y = 0 ; cmds[y] && e->cmda[y]; y++) {
1121                         if (strcasecmp(e->cmda[y], cmds[y]))
1122                                 break;
1123                 }
1124                 if (e->cmda[y] == NULL) {       /* no more words in candidate */
1125                         if (cmds[y] == NULL)    /* this is an exact match, cannot do better */
1126                                 break;
1127                         /* here the search key is longer than the candidate */
1128                         if (match_type != 0)    /* but we look for almost exact match... */
1129                                 continue;       /* so we skip this one. */
1130                         /* otherwise we like it (case 0) */
1131                 } else {                        /* still words in candidate */
1132                         if (cmds[y] == NULL)    /* search key is shorter, not good */
1133                                 continue;
1134                         /* if we get here, both words exist but there is a mismatch */
1135                         if (match_type == 0)    /* not the one we look for */
1136                                 continue;
1137                         if (match_type == 1)    /* not the one we look for */
1138                                 continue;
1139                         if (cmds[y+1] != NULL || e->cmda[y+1] != NULL)  /* not the one we look for */
1140                                 continue;
1141                         /* we are in case match_type == -1 and mismatch on last word */
1142                 }
1143                 if (cand == NULL || y > matchlen)       /* remember the candidate */
1144                         cand = e;
1145         }
1146         return e ? e : cand;
1147 }
1148
1149 static char *find_best(char *argv[])
1150 {
1151         static char cmdline[80];
1152         int x;
1153         /* See how close we get, then print the candidate */
1154         char *myargv[AST_MAX_CMD_LEN];
1155         for (x=0;x<AST_MAX_CMD_LEN;x++)
1156                 myargv[x]=NULL;
1157         AST_LIST_LOCK(&helpers);
1158         for (x=0;argv[x];x++) {
1159                 myargv[x] = argv[x];
1160                 if (!find_cli(myargv, -1))
1161                         break;
1162         }
1163         AST_LIST_UNLOCK(&helpers);
1164         ast_join(cmdline, sizeof(cmdline), myargv);
1165         return cmdline;
1166 }
1167
1168 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1169 {
1170         if (e->deprecate_cmd) {
1171                 __ast_cli_unregister(e->deprecate_cmd, e);
1172         }
1173         if (e->inuse) {
1174                 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1175         } else {
1176                 AST_LIST_LOCK(&helpers);
1177                 AST_LIST_REMOVE(&helpers, e, list);
1178                 AST_LIST_UNLOCK(&helpers);
1179         }
1180         return 0;
1181 }
1182
1183 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1184 {
1185         struct ast_cli_entry *cur;
1186         char fulle[80] ="";
1187         int lf, ret = -1;
1188         
1189         ast_join(fulle, sizeof(fulle), e->cmda);
1190         AST_LIST_LOCK(&helpers);
1191         
1192         if (find_cli(e->cmda, 1)) {
1193                 AST_LIST_UNLOCK(&helpers);
1194                 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
1195                 goto done;
1196         }
1197         e->_full_cmd = ast_strdup(fulle);
1198         if (!e->_full_cmd)
1199                 goto done;
1200
1201         if (ed) {
1202                 e->deprecated = 1;
1203                 e->summary = ed->summary;
1204                 e->usage = ed->usage;
1205                 /* XXX If command A deprecates command B, and command B deprecates command C...
1206                    Do we want to show command A or command B when telling the user to use new syntax?
1207                    This currently would show command A.
1208                    To show command B, you just need to always use ed->_full_cmd.
1209                  */
1210                 e->_deprecated_by = S_OR(ed->_deprecated_by, ed->_full_cmd);
1211         } else {
1212                 e->deprecated = 0;
1213         }
1214
1215         lf = strlen(fulle);
1216         AST_LIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1217                 int len = strlen(cur->_full_cmd);
1218                 if (lf < len)
1219                         len = lf;
1220                 if (strncasecmp(fulle, cur->_full_cmd, len) < 0) {
1221                         AST_LIST_INSERT_BEFORE_CURRENT(&helpers, e, list); 
1222                         break;
1223                 }
1224         }
1225         AST_LIST_TRAVERSE_SAFE_END;
1226
1227         if (!cur)
1228                 AST_LIST_INSERT_TAIL(&helpers, e, list); 
1229         ret = 0;        /* success */
1230
1231 done:
1232         AST_LIST_UNLOCK(&helpers);
1233
1234         if (e->deprecate_cmd) {
1235                 /* This command deprecates another command.  Register that one also. */
1236                 __ast_cli_register(e->deprecate_cmd, e);
1237         }
1238         
1239         return ret;
1240 }
1241
1242 /* wrapper function, so we can unregister deprecated commands recursively */
1243 int ast_cli_unregister(struct ast_cli_entry *e)
1244 {
1245         return __ast_cli_unregister(e, NULL);
1246 }
1247
1248 /* wrapper function, so we can register deprecated commands recursively */
1249 int ast_cli_register(struct ast_cli_entry *e)
1250 {
1251         return __ast_cli_register(e, NULL);
1252 }
1253
1254 /*
1255  * register/unregister an array of entries.
1256  */
1257 void ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1258 {
1259         int i;
1260
1261         for (i = 0; i < len; i++)
1262                 ast_cli_register(e + i);
1263 }
1264
1265 void ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1266 {
1267         int i;
1268
1269         for (i = 0; i < len; i++)
1270                 ast_cli_unregister(e + i);
1271 }
1272
1273
1274 /*! \brief helper for help_workhorse and final part of
1275  * handle_help. if locked = 0 it's just help_workhorse,
1276  * otherwise assume the list is already locked and print
1277  * an error message if not found.
1278  */
1279 static int help1(int fd, char *match[], int locked)
1280 {
1281         char matchstr[80] = "";
1282         struct ast_cli_entry *e;
1283         int len = 0;
1284         int found = 0;
1285         struct cli_iterator i = { NULL, NULL};
1286
1287         if (match) {
1288                 ast_join(matchstr, sizeof(matchstr), match);
1289                 len = strlen(matchstr);
1290         }
1291         if (!locked)
1292                 AST_LIST_LOCK(&helpers);
1293         while ( (e = cli_next(&i)) ) {
1294                 /* Hide commands that start with '_' */
1295                 if (e->_full_cmd[0] == '_')
1296                         continue;
1297                 /* Hide commands that are marked as deprecated. */
1298                 if (e->deprecated)
1299                         continue;
1300                 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1301                         continue;
1302                 ast_cli(fd, "%25.25s  %s\n", e->_full_cmd, e->summary);
1303                 found++;
1304         }
1305         AST_LIST_UNLOCK(&helpers);
1306         if (!locked && !found && matchstr[0])
1307                 ast_cli(fd, "No such command '%s'.\n", matchstr);
1308         return 0;
1309 }
1310
1311 static int help_workhorse(int fd, char *match[])
1312 {
1313         return help1(fd, match, 0 /* do not print errors */);
1314 }
1315
1316 static int handle_help(int fd, int argc, char *argv[])
1317 {
1318         char fullcmd[80];
1319         struct ast_cli_entry *e;
1320
1321         if (argc < 1)
1322                 return RESULT_SHOWUSAGE;
1323         if (argc == 1)
1324                 return help_workhorse(fd, NULL);
1325
1326         AST_LIST_LOCK(&helpers);
1327         e = find_cli(argv + 1, 1);      /* try exact match first */
1328         if (!e)
1329                 return help1(fd, argv + 1, 1 /* locked */);
1330         if (e->usage)
1331                 ast_cli(fd, "%s", e->usage);
1332         else {
1333                 ast_join(fullcmd, sizeof(fullcmd), argv+1);
1334                 ast_cli(fd, "No help text available for '%s'.\n", fullcmd);
1335         }
1336         AST_LIST_UNLOCK(&helpers);
1337         return RESULT_SUCCESS;
1338 }
1339
1340 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1341 {
1342         char *dup, *cur;
1343         int x = 0;
1344         int quoted = 0;
1345         int escaped = 0;
1346         int whitespace = 1;
1347
1348         *trailingwhitespace = 0;
1349         if (s == NULL)  /* invalid, though! */
1350                 return NULL;
1351         /* make a copy to store the parsed string */
1352         if (!(dup = ast_strdup(s)))
1353                 return NULL;
1354
1355         cur = dup;
1356         /* scan the original string copying into cur when needed */
1357         for (; *s ; s++) {
1358                 if (x >= max - 1) {
1359                         ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1360                         break;
1361                 }
1362                 if (*s == '"' && !escaped) {
1363                         quoted = !quoted;
1364                         if (quoted && whitespace) {
1365                                 /* start a quoted string from previous whitespace: new argument */
1366                                 argv[x++] = cur;
1367                                 whitespace = 0;
1368                         }
1369                 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1370                         /* If we are not already in whitespace, and not in a quoted string or
1371                            processing an escape sequence, and just entered whitespace, then
1372                            finalize the previous argument and remember that we are in whitespace
1373                         */
1374                         if (!whitespace) {
1375                                 *cur++ = '\0';
1376                                 whitespace = 1;
1377                         }
1378                 } else if (*s == '\\' && !escaped) {
1379                         escaped = 1;
1380                 } else {
1381                         if (whitespace) {
1382                                 /* we leave whitespace, and are not quoted. So it's a new argument */
1383                                 argv[x++] = cur;
1384                                 whitespace = 0;
1385                         }
1386                         *cur++ = *s;
1387                         escaped = 0;
1388                 }
1389         }
1390         /* Null terminate */
1391         *cur++ = '\0';
1392         /* XXX put a NULL in the last argument, because some functions that take
1393          * the array may want a null-terminated array.
1394          * argc still reflects the number of non-NULL entries.
1395          */
1396         argv[x] = NULL;
1397         *argc = x;
1398         *trailingwhitespace = whitespace;
1399         return dup;
1400 }
1401
1402 /*! \brief Return the number of unique matches for the generator */
1403 int ast_cli_generatornummatches(const char *text, const char *word)
1404 {
1405         int matches = 0, i = 0;
1406         char *buf = NULL, *oldbuf = NULL;
1407
1408         while ((buf = ast_cli_generator(text, word, i++))) {
1409                 if (!oldbuf || strcmp(buf,oldbuf))
1410                         matches++;
1411                 if (oldbuf)
1412                         free(oldbuf);
1413                 oldbuf = buf;
1414         }
1415         if (oldbuf)
1416                 free(oldbuf);
1417         return matches;
1418 }
1419
1420 char **ast_cli_completion_matches(const char *text, const char *word)
1421 {
1422         char **match_list = NULL, *retstr, *prevstr;
1423         size_t match_list_len, max_equal, which, i;
1424         int matches = 0;
1425
1426         /* leave entry 0 free for the longest common substring */
1427         match_list_len = 1;
1428         while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1429                 if (matches + 1 >= match_list_len) {
1430                         match_list_len <<= 1;
1431                         if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1432                                 return NULL;
1433                 }
1434                 match_list[++matches] = retstr;
1435         }
1436
1437         if (!match_list)
1438                 return match_list; /* NULL */
1439
1440         /* Find the longest substring that is common to all results
1441          * (it is a candidate for completion), and store a copy in entry 0.
1442          */
1443         prevstr = match_list[1];
1444         max_equal = strlen(prevstr);
1445         for (which = 2; which <= matches; which++) {
1446                 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1447                         continue;
1448                 max_equal = i;
1449         }
1450
1451         if (!(retstr = ast_malloc(max_equal + 1)))
1452                 return NULL;
1453         
1454         ast_copy_string(retstr, match_list[1], max_equal + 1);
1455         match_list[0] = retstr;
1456
1457         /* ensure that the array is NULL terminated */
1458         if (matches + 1 >= match_list_len) {
1459                 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1460                         return NULL;
1461         }
1462         match_list[matches + 1] = NULL;
1463
1464         return match_list;
1465 }
1466
1467 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1468 {
1469         char *argv[AST_MAX_ARGS];
1470         struct ast_cli_entry *e;
1471         struct cli_iterator i = { NULL, NULL };
1472         int x = 0, argindex, matchlen;
1473         int matchnum=0;
1474         char *ret = NULL;
1475         char matchstr[80] = "";
1476         int tws = 0;
1477         char *dup = parse_args(text, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws);
1478
1479         if (!dup)       /* error */
1480                 return NULL;
1481         argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1482         /* rebuild the command, ignore tws */
1483         ast_join(matchstr, sizeof(matchstr)-1, argv);
1484         matchlen = strlen(matchstr);
1485         if (tws) {
1486                 strcat(matchstr, " "); /* XXX */
1487                 if (matchlen)
1488                         matchlen++;
1489         }
1490         if (lock)
1491                 AST_LIST_LOCK(&helpers);
1492         while( !ret && (e = cli_next(&i)) ) {
1493                 int lc = strlen(e->_full_cmd);
1494                 if (e->_full_cmd[0] != '_' && lc > 0 && matchlen <= lc &&
1495                                 !strncasecmp(matchstr, e->_full_cmd, matchlen)) {
1496                         /* Found initial part, return a copy of the next word... */
1497                         if (e->cmda[argindex] && ++matchnum > state)
1498                                 ret = strdup(e->cmda[argindex]); /* we need a malloced string */
1499                 } else if (e->generator && !strncasecmp(matchstr, e->_full_cmd, lc) && matchstr[lc] < 33) {
1500                         /* We have a command in its entirity within us -- theoretically only one
1501                            command can have this occur */
1502                         ret = e->generator(matchstr, word, argindex, state);
1503                 }
1504         }
1505         if (lock)
1506                 AST_LIST_UNLOCK(&helpers);
1507         free(dup);
1508         return ret;
1509 }
1510
1511 char *ast_cli_generator(const char *text, const char *word, int state)
1512 {
1513         return __ast_cli_generator(text, word, state, 1);
1514 }
1515
1516 int ast_cli_command(int fd, const char *s)
1517 {
1518         char *argv[AST_MAX_ARGS];
1519         struct ast_cli_entry *e;
1520         int x;
1521         char *dup;
1522         int tws;
1523         
1524         if (!(dup = parse_args(s, &x, argv, sizeof(argv) / sizeof(argv[0]), &tws)))
1525                 return -1;
1526
1527         /* We need at least one entry, or ignore */
1528         if (x > 0) {
1529                 AST_LIST_LOCK(&helpers);
1530                 e = find_cli(argv, 0);
1531                 if (e)
1532                         e->inuse++;
1533                 AST_LIST_UNLOCK(&helpers);
1534                 if (e) {
1535                         switch(e->handler(fd, x, argv)) {
1536                         case RESULT_SHOWUSAGE:
1537                                 if (e->usage)
1538                                         ast_cli(fd, "%s", e->usage);
1539                                 else
1540                                         ast_cli(fd, "Invalid usage, but no usage information available.\n");
1541                                 break;
1542                         default:
1543                                 AST_LIST_LOCK(&helpers);
1544                                 if (e->deprecated == 1) {
1545                                         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);
1546                                         e->deprecated = 2;
1547                                 }
1548                                 AST_LIST_UNLOCK(&helpers);
1549                                 break;
1550                         }
1551                 } else 
1552                         ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1553                 if (e)
1554                         ast_atomic_fetchadd_int(&e->inuse, -1);
1555         }
1556         free(dup);
1557         
1558         return 0;
1559 }