Resolve a subtle bug where we would never successfully be able to get
[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 "asterisk/_private.h"
31 #include "asterisk/paths.h"     /* use ast_config_AST_MODULE_DIR */
32 #include <sys/signal.h>
33 #include <signal.h>
34 #include <ctype.h>
35 #include <regex.h>
36
37 #include "asterisk/cli.h"
38 #include "asterisk/linkedlists.h"
39 #include "asterisk/module.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/app.h"
44 #include "asterisk/lock.h"
45 #include "editline/readline/readline.h"
46 #include "asterisk/threadstorage.h"
47
48 /*!
49  * \brief map a debug or verbose value to a filename
50  */
51 struct ast_debug_file {
52         unsigned int level;
53         AST_RWLIST_ENTRY(ast_debug_file) entry;
54         char filename[0];
55 };
56
57 AST_RWLIST_HEAD(debug_file_list, ast_debug_file);
58
59 /*! list of filenames and their debug settings */
60 static struct debug_file_list debug_files;
61 /*! list of filenames and their verbose settings */
62 static struct debug_file_list verbose_files;
63
64 AST_THREADSTORAGE(ast_cli_buf);
65
66 /*! \brief Initial buffer size for resulting strings in ast_cli() */
67 #define AST_CLI_INITLEN   256
68
69 void ast_cli(int fd, const char *fmt, ...)
70 {
71         int res;
72         struct ast_str *buf;
73         va_list ap;
74
75         if (!(buf = ast_str_thread_get(&ast_cli_buf, AST_CLI_INITLEN)))
76                 return;
77
78         va_start(ap, fmt);
79         res = ast_str_set_va(&buf, 0, fmt, ap);
80         va_end(ap);
81
82         if (res != AST_DYNSTR_BUILD_FAILED)
83                 ast_carefulwrite(fd, buf->str, strlen(buf->str), 100);
84 }
85
86 unsigned int ast_debug_get_by_file(const char *file) 
87 {
88         struct ast_debug_file *adf;
89         unsigned int res = 0;
90
91         AST_RWLIST_RDLOCK(&debug_files);
92         AST_LIST_TRAVERSE(&debug_files, adf, entry) {
93                 if (!strncasecmp(adf->filename, file, strlen(adf->filename))) {
94                         res = adf->level;
95                         break;
96                 }
97         }
98         AST_RWLIST_UNLOCK(&debug_files);
99
100         return res;
101 }
102
103 unsigned int ast_verbose_get_by_file(const char *file) 
104 {
105         struct ast_debug_file *adf;
106         unsigned int res = 0;
107
108         AST_RWLIST_RDLOCK(&verbose_files);
109         AST_LIST_TRAVERSE(&verbose_files, adf, entry) {
110                 if (!strncasecmp(adf->filename, file, strlen(file))) {
111                         res = adf->level;
112                         break;
113                 }
114         }
115         AST_RWLIST_UNLOCK(&verbose_files);
116
117         return res;
118 }
119
120 static AST_RWLIST_HEAD_STATIC(helpers, ast_cli_entry);
121
122 static char *complete_fn(const char *word, int state)
123 {
124         char *c, *d;
125         char filename[PATH_MAX];
126
127         if (word[0] == '/')
128                 ast_copy_string(filename, word, sizeof(filename));
129         else
130                 snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
131
132         c = d = filename_completion_function(filename, state);
133         
134         if (c && word[0] != '/')
135                 c += (strlen(ast_config_AST_MODULE_DIR) + 1);
136         if (c)
137                 c = ast_strdup(c);
138         if (d)
139                 free(d);
140         
141         return c;
142 }
143
144 static char *handle_load(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
145 {
146         /* "module load <mod>" */
147         switch (cmd) {
148         case CLI_INIT:
149                 e->command = "module load";
150                 e->usage =
151                         "Usage: module load <module name>\n"
152                         "       Loads the specified module into Asterisk.\n";
153                 return NULL;
154
155         case CLI_GENERATE:
156                 if (a->pos != e->args)
157                         return NULL;
158                 return complete_fn(a->word, a->n);
159         }
160         if (a->argc != e->args + 1)
161                 return CLI_SHOWUSAGE;
162         if (ast_load_resource(a->argv[e->args])) {
163                 ast_cli(a->fd, "Unable to load module %s\n", a->argv[e->args]);
164                 return CLI_FAILURE;
165         }
166         return CLI_SUCCESS;
167 }
168
169 static char *handle_load_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
170 {
171         char *res = handle_load(e, cmd, a);
172         if (cmd == CLI_INIT)
173                 e->command = "load";
174         return res;
175 }
176
177 static char *handle_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
178 {
179         int x;
180
181         switch (cmd) {
182         case CLI_INIT:
183                 e->command = "module reload";
184                 e->usage =
185                         "Usage: module reload [module ...]\n"
186                         "       Reloads configuration files for all listed modules which support\n"
187                         "       reloading, or for all supported modules if none are listed.\n";
188                 return NULL;
189
190         case CLI_GENERATE:
191                 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 1);
192         }
193         if (a->argc == e->args) {
194                 ast_module_reload(NULL);
195                 return CLI_SUCCESS;
196         }
197         for (x = e->args; x < a->argc; x++) {
198                 int res = ast_module_reload(a->argv[x]);
199                 /* XXX reload has multiple error returns, including -1 on error and 2 on success */
200                 switch (res) {
201                 case 0:
202                         ast_cli(a->fd, "No such module '%s'\n", a->argv[x]);
203                         break;
204                 case 1:
205                         ast_cli(a->fd, "Module '%s' does not support reload\n", a->argv[x]);
206                         break;
207                 }
208         }
209         return CLI_SUCCESS;
210 }
211
212 static char *handle_reload_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
213 {
214         char *s = handle_reload(e, cmd, a);
215         if (cmd == CLI_INIT)            /* override command name */
216                 e->command = "reload";
217         return s;
218 }
219
220 /*! 
221  * \brief Find the debug or verbose file setting 
222  * \arg debug 1 for debug, 0 for verbose
223  */
224 static struct ast_debug_file *find_debug_file(const char *fn, unsigned int debug)
225 {
226         struct ast_debug_file *df = NULL;
227         struct debug_file_list *dfl = debug ? &debug_files : &verbose_files;
228
229         AST_LIST_TRAVERSE(dfl, df, entry) {
230                 if (!strcasecmp(df->filename, fn))
231                         break;
232         }
233
234         return df;
235 }
236
237 static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
238 {
239         int oldval;
240         int newlevel;
241         int atleast = 0;
242         int fd = a->fd;
243         int argc = a->argc;
244         char **argv = a->argv;
245         int *dst;
246         char *what;
247         struct debug_file_list *dfl;
248         struct ast_debug_file *adf;
249         char *fn;
250
251         switch (cmd) {
252         case CLI_INIT:
253                 e->command = "core set {debug|verbose} [off|atleast]";
254                 e->usage =
255                         "Usage: core set {debug|verbose} [atleast] <level> [filename]\n"
256                         "       core set {debug|verbose} off\n"
257                         "       Sets level of debug or verbose messages to be displayed or \n"
258                         "       sets a filename to display debug messages from.\n"
259                         "       0 or off means no messages should be displayed.\n"
260                         "       Equivalent to -d[d[...]] or -v[v[v...]] on startup\n";
261                 return NULL;
262
263         case CLI_GENERATE:
264                 return NULL;
265         }
266         /* all the above return, so we proceed with the handler.
267          * we are guaranteed to be called with argc >= e->args;
268          */
269
270         if (argc < e->args)
271                 return CLI_SHOWUSAGE;
272         if (!strcasecmp(argv[e->args - 2], "debug")) {
273                 dst = &option_debug;
274                 oldval = option_debug;
275                 what = "Core debug";
276         } else {
277                 dst = &option_verbose;
278                 oldval = option_verbose;
279                 what = "Verbosity";
280         }
281         if (argc == e->args && !strcasecmp(argv[e->args - 1], "off")) {
282                 unsigned int debug = (*what == 'C');
283                 newlevel = 0;
284
285                 dfl = debug ? &debug_files : &verbose_files;
286
287                 AST_RWLIST_WRLOCK(dfl);
288                 while ((adf = AST_RWLIST_REMOVE_HEAD(dfl, entry)))
289                         ast_free(adf);
290                 ast_clear_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
291                 AST_RWLIST_UNLOCK(dfl);
292
293                 goto done;
294         }
295         if (!strcasecmp(argv[e->args-1], "atleast"))
296                 atleast = 1;
297         if (argc != e->args + atleast && argc != e->args + atleast + 1)
298                 return CLI_SHOWUSAGE;
299         if (sscanf(argv[e->args + atleast - 1], "%d", &newlevel) != 1)
300                 return CLI_SHOWUSAGE;
301         if (argc == e->args + atleast + 1) {
302                 unsigned int debug = (*what == 'C');
303                 dfl = debug ? &debug_files : &verbose_files;
304
305                 fn = argv[e->args + atleast];
306
307                 AST_RWLIST_WRLOCK(dfl);
308
309                 if ((adf = find_debug_file(fn, debug)) && !newlevel) {
310                         AST_RWLIST_REMOVE(dfl, adf, entry);
311                         if (AST_RWLIST_EMPTY(dfl))
312                                 ast_clear_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
313                         AST_RWLIST_UNLOCK(dfl);
314                         ast_cli(fd, "%s was %d and has been set to 0 for '%s'\n", what, adf->level, fn);
315                         ast_free(adf);
316                         return CLI_SUCCESS;
317                 }
318
319                 if (adf) {
320                         if ((atleast && newlevel < adf->level) || adf->level == newlevel) {
321                                 ast_cli(fd, "%s is %d for '%s'\n", what, adf->level, fn);
322                                 AST_RWLIST_UNLOCK(dfl);
323                                 return CLI_SUCCESS;
324                         }
325                 } else if (!(adf = ast_calloc(1, sizeof(*adf) + strlen(fn) + 1))) {
326                         AST_RWLIST_UNLOCK(dfl);
327                         return CLI_FAILURE;
328                 }
329
330                 oldval = adf->level;
331                 adf->level = newlevel;
332                 strcpy(adf->filename, fn);
333
334                 ast_set_flag(&ast_options, debug ? AST_OPT_FLAG_DEBUG_FILE : AST_OPT_FLAG_VERBOSE_FILE);
335
336                 AST_RWLIST_INSERT_TAIL(dfl, adf, entry);
337                 AST_RWLIST_UNLOCK(dfl);
338
339                 ast_cli(fd, "%s was %d and has been set to %d for '%s'\n", what, oldval, adf->level, adf->filename);
340
341                 return CLI_SUCCESS;
342         }
343
344 done:
345         if (!atleast || newlevel > *dst)
346                 *dst = newlevel;
347         if (oldval > 0 && *dst == 0)
348                 ast_cli(fd, "%s is now OFF\n", what);
349         else if (*dst > 0) {
350                 if (oldval == *dst)
351                         ast_cli(fd, "%s is at least %d\n", what, *dst);
352                 else
353                         ast_cli(fd, "%s was %d and is now %d\n", what, oldval, *dst);
354         }
355
356         return CLI_SUCCESS;
357 }
358
359 static char *handle_logger_mute(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
360 {
361         switch (cmd) {
362         case CLI_INIT:
363                 e->command = "logger mute";
364                 e->usage = 
365                         "Usage: logger mute\n"
366                         "       Disables logging output to the current console, making it possible to\n"
367                         "       gather information without being disturbed by scrolling lines.\n";
368                 return NULL;
369         case CLI_GENERATE:
370                 return NULL;
371         }
372
373         if (a->argc < 2 || a->argc > 3)
374                 return CLI_SHOWUSAGE;
375
376         if (a->argc == 3 && !strcasecmp(a->argv[2], "silent"))
377                 ast_console_toggle_mute(a->fd, 1);
378         else
379                 ast_console_toggle_mute(a->fd, 0);
380
381         return CLI_SUCCESS;
382 }
383
384 static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
385 {
386         /* "module unload mod_1 [mod_2 .. mod_N]" */
387         int x;
388         int force = AST_FORCE_SOFT;
389         char *s;
390
391         switch (cmd) {
392         case CLI_INIT:
393                 e->command = "module unload";
394                 e->usage =
395                         "Usage: module unload [-f|-h] <module_1> [<module_2> ... ]\n"
396                         "       Unloads the specified module from Asterisk. The -f\n"
397                         "       option causes the module to be unloaded even if it is\n"
398                         "       in use (may cause a crash) and the -h module causes the\n"
399                         "       module to be unloaded even if the module says it cannot, \n"
400                         "       which almost always will cause a crash.\n";
401                 return NULL;
402
403         case CLI_GENERATE:
404                 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
405         }
406         if (a->argc < e->args + 1)
407                 return CLI_SHOWUSAGE;
408         x = e->args;    /* first argument */
409         s = a->argv[x];
410         if (s[0] == '-') {
411                 if (s[1] == 'f')
412                         force = AST_FORCE_FIRM;
413                 else if (s[1] == 'h')
414                         force = AST_FORCE_HARD;
415                 else
416                         return CLI_SHOWUSAGE;
417                 if (a->argc < e->args + 2)      /* need at least one module name */
418                         return CLI_SHOWUSAGE;
419                 x++;    /* skip this argument */
420         }
421
422         for (; x < a->argc; x++) {
423                 if (ast_unload_resource(a->argv[x], force)) {
424                         ast_cli(a->fd, "Unable to unload resource %s\n", a->argv[x]);
425                         return CLI_FAILURE;
426                 }
427         }
428         return CLI_SUCCESS;
429 }
430
431 static char *handle_unload_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
432 {
433         char *res = handle_unload(e, cmd, a);
434         if (cmd == CLI_INIT)
435                 e->command = "unload";  /* XXX override */
436         return res;
437 }
438
439 #define MODLIST_FORMAT  "%-30s %-40.40s %-10d\n"
440 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s\n"
441
442 AST_MUTEX_DEFINE_STATIC(climodentrylock);
443 static int climodentryfd = -1;
444
445 static int modlist_modentry(const char *module, const char *description, int usecnt, const char *like)
446 {
447         /* Comparing the like with the module */
448         if (strcasestr(module, like) ) {
449                 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
450                 return 1;
451         } 
452         return 0;
453 }
454
455 static void print_uptimestr(int fd, struct timeval timeval, const char *prefix, int printsec)
456 {
457         int x; /* the main part - years, weeks, etc. */
458         struct ast_str *out;
459
460 #define SECOND (1)
461 #define MINUTE (SECOND*60)
462 #define HOUR (MINUTE*60)
463 #define DAY (HOUR*24)
464 #define WEEK (DAY*7)
465 #define YEAR (DAY*365)
466 #define NEEDCOMMA(x) ((x)? ",": "")     /* define if we need a comma */
467         if (timeval.tv_sec < 0) /* invalid, nothing to show */
468                 return;
469
470         if (printsec)  {        /* plain seconds output */
471                 ast_cli(fd, "%s: %lu\n", prefix, (u_long)timeval.tv_sec);
472                 return;
473         }
474         out = ast_str_alloca(256);
475         if (timeval.tv_sec > YEAR) {
476                 x = (timeval.tv_sec / YEAR);
477                 timeval.tv_sec -= (x * YEAR);
478                 ast_str_append(&out, 0, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
479         }
480         if (timeval.tv_sec > WEEK) {
481                 x = (timeval.tv_sec / WEEK);
482                 timeval.tv_sec -= (x * WEEK);
483                 ast_str_append(&out, 0, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
484         }
485         if (timeval.tv_sec > DAY) {
486                 x = (timeval.tv_sec / DAY);
487                 timeval.tv_sec -= (x * DAY);
488                 ast_str_append(&out, 0, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
489         }
490         if (timeval.tv_sec > HOUR) {
491                 x = (timeval.tv_sec / HOUR);
492                 timeval.tv_sec -= (x * HOUR);
493                 ast_str_append(&out, 0, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
494         }
495         if (timeval.tv_sec > MINUTE) {
496                 x = (timeval.tv_sec / MINUTE);
497                 timeval.tv_sec -= (x * MINUTE);
498                 ast_str_append(&out, 0, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
499         }
500         x = timeval.tv_sec;
501         if (x > 0 || out->used == 0)    /* if there is nothing, print 0 seconds */
502                 ast_str_append(&out, 0, "%d second%s ", x, ESS(x));
503         ast_cli(fd, "%s: %s\n", prefix, out->str);
504 }
505
506 static char * handle_showuptime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
507 {
508         struct timeval curtime = ast_tvnow();
509         int printsec;
510
511         switch (cmd) {
512         case CLI_INIT:
513                 e->command = "core show uptime [seconds]";
514                 e->usage =
515                         "Usage: core show uptime [seconds]\n"
516                         "       Shows Asterisk uptime information.\n"
517                         "       The seconds word returns the uptime in seconds only.\n";
518                 return NULL;
519
520         case CLI_GENERATE:
521                 return NULL;
522         }
523         /* regular handler */
524         if (a->argc == e->args && !strcasecmp(a->argv[e->args-1],"seconds"))
525                 printsec = 1;
526         else if (a->argc == e->args-1)
527                 printsec = 0;
528         else
529                 return CLI_SHOWUSAGE;
530         if (ast_startuptime.tv_sec)
531                 print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
532         if (ast_lastreloadtime.tv_sec)
533                 print_uptimestr(a->fd, ast_tvsub(curtime, ast_lastreloadtime), "Last reload", printsec);
534         return CLI_SUCCESS;
535 }
536
537 static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
538 {
539         char *like;
540
541         switch (cmd) {
542         case CLI_INIT:
543                 e->command = "module show [like]";
544                 e->usage =
545                         "Usage: module show [like keyword]\n"
546                         "       Shows Asterisk modules currently in use, and usage statistics.\n";
547                 return NULL;
548
549         case CLI_GENERATE:
550                 if (a->pos == e->args)
551                         return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
552                 else
553                         return NULL;
554         }
555         /* all the above return, so we proceed with the handler.
556          * we are guaranteed to have argc >= e->args
557          */
558         if (a->argc == e->args - 1)
559                 like = "";
560         else if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args-1], "like") )
561                 like = a->argv[e->args];
562         else
563                 return CLI_SHOWUSAGE;
564                 
565         ast_mutex_lock(&climodentrylock);
566         climodentryfd = a->fd; /* global, protected by climodentrylock */
567         ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
568         ast_cli(a->fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
569         climodentryfd = -1;
570         ast_mutex_unlock(&climodentrylock);
571         return CLI_SUCCESS;
572 }
573 #undef MODLIST_FORMAT
574 #undef MODLIST_FORMAT2
575
576 static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
577 {
578         struct timeval curtime = ast_tvnow();
579         int showuptime, printsec;
580
581         switch (cmd) {
582         case CLI_INIT:
583                 e->command = "core show calls [uptime]";
584                 e->usage =
585                         "Usage: core show calls [uptime] [seconds]\n"
586                         "       Lists number of currently active calls and total number of calls\n"
587                         "       processed through PBX since last restart. If 'uptime' is specified\n"
588                         "       the system uptime is also displayed. If 'seconds' is specified in\n"
589                         "       addition to 'uptime', the system uptime is displayed in seconds.\n";
590                 return NULL;
591
592         case CLI_GENERATE:
593                 if (a->pos != e->args)
594                         return NULL;
595                 return a->n == 0  ? ast_strdup("seconds") : NULL;
596         }
597
598         /* regular handler */
599         if (a->argc >= e->args && !strcasecmp(a->argv[e->args-1],"uptime")) {
600                 showuptime = 1;
601
602                 if (a->argc == e->args+1 && !strcasecmp(a->argv[e->args],"seconds"))
603                         printsec = 1;
604                 else if (a->argc == e->args)
605                         printsec = 0;
606                 else
607                         return CLI_SHOWUSAGE;
608         } else if (a->argc == e->args-1) {
609                 showuptime = 0;
610                 printsec = 0;
611         } else
612                 return CLI_SHOWUSAGE;
613
614         if (option_maxcalls) {
615                 ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
616                    ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
617                    ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
618         } else {
619                 ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
620         }
621    
622         ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
623
624         if (ast_startuptime.tv_sec && showuptime) {
625                 print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
626         }
627
628         return RESULT_SUCCESS;
629 }
630
631 static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
632 {
633 #define FORMAT_STRING  "%-20.20s %-20.20s %-7.7s %-30.30s\n"
634 #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
635 #define CONCISE_FORMAT_STRING  "%s!%s!%s!%d!%s!%s!%s!%s!%s!%d!%s!%s!%s\n"
636 #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"
637 #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"
638
639         struct ast_channel *c = NULL;
640         int numchans = 0, concise = 0, verbose = 0, count = 0;
641         int fd, argc;
642         char **argv;
643
644         switch (cmd) {
645         case CLI_INIT:
646                 e->command = "core show channels [concise|verbose|count]";
647                 e->usage =
648                         "Usage: core show channels [concise|verbose|count]\n"
649                         "       Lists currently defined channels and some information about them. If\n"
650                         "       'concise' is specified, the format is abridged and in a more easily\n"
651                         "       machine parsable format. If 'verbose' is specified, the output includes\n"
652                         "       more and longer fields. If 'count' is specified only the channel and call\n"
653                         "       count is output.\n"
654                         "       The 'concise' option is deprecated and will be removed from future versions\n"
655                         "       of Asterisk.\n";
656                 return NULL;
657
658         case CLI_GENERATE:
659                 return NULL;
660         }
661         fd = a->fd;
662         argc = a->argc;
663         argv = a->argv;
664
665         if (a->argc == e->args) {
666                 if (!strcasecmp(argv[e->args-1],"concise"))
667                         concise = 1;
668                 else if (!strcasecmp(argv[e->args-1],"verbose"))
669                         verbose = 1;
670                 else if (!strcasecmp(argv[e->args-1],"count"))
671                         count = 1;
672                 else
673                         return CLI_SHOWUSAGE;
674         } else if (a->argc != e->args - 1)
675                 return CLI_SHOWUSAGE;
676
677         if (!count) {
678                 if (!concise && !verbose)
679                         ast_cli(fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
680                 else if (verbose)
681                         ast_cli(fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data", 
682                                 "CallerID", "Duration", "Accountcode", "BridgedTo");
683         }
684
685         while ((c = ast_channel_walk_locked(c)) != NULL) {
686                 struct ast_channel *bc = ast_bridged_channel(c);
687                 char durbuf[10] = "-";
688
689                 if (!count) {
690                         if ((concise || verbose)  && c->cdr && !ast_tvzero(c->cdr->start)) {
691                                 int duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
692                                 if (verbose) {
693                                         int durh = duration / 3600;
694                                         int durm = (duration % 3600) / 60;
695                                         int durs = duration % 60;
696                                         snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
697                                 } else {
698                                         snprintf(durbuf, sizeof(durbuf), "%d", duration);
699                                 }                               
700                         }
701                         if (concise) {
702                                 ast_cli(fd, CONCISE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
703                                         c->appl ? c->appl : "(None)",
704                                         S_OR(c->data, ""),      /* XXX different from verbose ? */
705                                         S_OR(c->cid.cid_num, ""),
706                                         S_OR(c->accountcode, ""),
707                                         c->amaflags, 
708                                         durbuf,
709                                         bc ? bc->name : "(None)",
710                                         c->uniqueid);
711                         } else if (verbose) {
712                                 ast_cli(fd, VERBOSE_FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
713                                         c->appl ? c->appl : "(None)",
714                                         c->data ? S_OR(c->data, "(Empty)" ): "(None)",
715                                         S_OR(c->cid.cid_num, ""),
716                                         durbuf,
717                                         S_OR(c->accountcode, ""),
718                                         bc ? bc->name : "(None)");
719                         } else {
720                                 char locbuf[40] = "(None)";
721                                 char appdata[40] = "(None)";
722                                 
723                                 if (!ast_strlen_zero(c->context) && !ast_strlen_zero(c->exten)) 
724                                         snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", c->exten, c->context, c->priority);
725                                 if (c->appl)
726                                         snprintf(appdata, sizeof(appdata), "%s(%s)", c->appl, S_OR(c->data, ""));
727                                 ast_cli(fd, FORMAT_STRING, c->name, locbuf, ast_state2str(c->_state), appdata);
728                         }
729                 }
730                 numchans++;
731                 ast_channel_unlock(c);
732         }
733         if (!concise) {
734                 ast_cli(fd, "%d active channel%s\n", numchans, ESS(numchans));
735                 if (option_maxcalls)
736                         ast_cli(fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
737                                 ast_active_calls(), option_maxcalls, ESS(ast_active_calls()),
738                                 ((double)ast_active_calls() / (double)option_maxcalls) * 100.0);
739                 else
740                         ast_cli(fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
741
742                 ast_cli(fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
743         }
744         return CLI_SUCCESS;
745         
746 #undef FORMAT_STRING
747 #undef FORMAT_STRING2
748 #undef CONCISE_FORMAT_STRING
749 #undef VERBOSE_FORMAT_STRING
750 #undef VERBOSE_FORMAT_STRING2
751 }
752
753 static char *handle_softhangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
754 {
755         struct ast_channel *c=NULL;
756
757         switch (cmd) {
758         case CLI_INIT:
759                 e->command = "channel request hangup";
760                 e->usage =
761                         "Usage: channel request hangup <channel>\n"
762                         "       Request that a channel be hung up. The hangup takes effect\n"
763                         "       the next time the driver reads or writes from the channel\n";
764                 return NULL;
765         case CLI_GENERATE:
766                 return ast_complete_channels(a->line, a->word, a->pos, a->n, 2);
767         }
768         if (a->argc != 4)
769                 return CLI_SHOWUSAGE;
770         c = ast_get_channel_by_name_locked(a->argv[3]);
771         if (c) {
772                 ast_cli(a->fd, "Requested Hangup on channel '%s'\n", c->name);
773                 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
774                 ast_channel_unlock(c);
775         } else
776                 ast_cli(a->fd, "%s is not a known channel\n", a->argv[2]);
777         return CLI_SUCCESS;
778 }
779
780 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
781
782 static char *handle_commandmatchesarray(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
783 {
784         char *buf, *obuf;
785         int buflen = 2048;
786         int len = 0;
787         char **matches;
788         int x, matchlen;
789         
790         switch (cmd) {
791         case CLI_INIT:
792                 e->command = "_command matchesarray";
793                 e->usage = 
794                         "Usage: _command matchesarray \"<line>\" text \n"
795                         "       This function is used internally to help with command completion and should.\n"
796                         "       never be called by the user directly.\n";
797                 return NULL;
798         case CLI_GENERATE:
799                 return NULL;
800         }
801
802         if (a->argc != 4)
803                 return CLI_SHOWUSAGE;
804         if (!(buf = ast_malloc(buflen)))
805                 return CLI_FAILURE;
806         buf[len] = '\0';
807         matches = ast_cli_completion_matches(a->argv[2], a->argv[3]);
808         if (matches) {
809                 for (x=0; matches[x]; x++) {
810                         matchlen = strlen(matches[x]) + 1;
811                         if (len + matchlen >= buflen) {
812                                 buflen += matchlen * 3;
813                                 obuf = buf;
814                                 if (!(buf = ast_realloc(obuf, buflen))) 
815                                         /* Memory allocation failure...  Just free old buffer and be done */
816                                         ast_free(obuf);
817                         }
818                         if (buf)
819                                 len += sprintf( buf + len, "%s ", matches[x]);
820                         ast_free(matches[x]);
821                         matches[x] = NULL;
822                 }
823                 ast_free(matches);
824         }
825
826         if (buf) {
827                 ast_cli(a->fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
828                 ast_free(buf);
829         } else
830                 ast_cli(a->fd, "NULL\n");
831
832         return CLI_SUCCESS;
833 }
834
835
836
837 static char *handle_commandnummatches(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
838 {
839         int matches = 0;
840
841         switch (cmd) {
842         case CLI_INIT:
843                 e->command = "_command nummatches";
844                 e->usage = 
845                         "Usage: _command nummatches \"<line>\" text \n"
846                         "       This function is used internally to help with command completion and should.\n"
847                         "       never be called by the user directly.\n";
848                 return NULL;
849         case CLI_GENERATE:
850                 return NULL;
851         }
852
853         if (a->argc != 4)
854                 return CLI_SHOWUSAGE;
855
856         matches = ast_cli_generatornummatches(a->argv[2], a->argv[3]);
857
858         ast_cli(a->fd, "%d", matches);
859
860         return CLI_SUCCESS;
861 }
862
863 static char *handle_commandcomplete(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
864 {
865         char *buf;
866         switch (cmd) {
867         case CLI_INIT:
868                 e->command = "_command complete";
869                 e->usage = 
870                         "Usage: _command complete \"<line>\" text state\n"
871                         "       This function is used internally to help with command completion and should.\n"
872                         "       never be called by the user directly.\n";
873                 return NULL;
874         case CLI_GENERATE:
875                 return NULL;
876         }
877         if (a->argc != 5)
878                 return CLI_SHOWUSAGE;
879         buf = __ast_cli_generator(a->argv[2], a->argv[3], atoi(a->argv[4]), 0);
880         if (buf) {
881                 ast_cli(a->fd, "%s", buf);
882                 ast_free(buf);
883         } else
884                 ast_cli(a->fd, "NULL\n");
885         return CLI_SUCCESS;
886 }
887
888 static char *handle_core_set_debug_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
889 {
890         struct ast_channel *c = NULL;
891         int is_all, is_off = 0;
892
893         switch (cmd) {
894         case CLI_INIT:
895                 e->command = "core set debug channel";
896                 e->usage =
897                         "Usage: core set debug channel <all|channel> [off]\n"
898                         "       Enables/disables debugging on all or on a specific channel.\n";
899                 return NULL;
900
901         case CLI_GENERATE:
902                 /* XXX remember to handle the optional "off" */
903                 if (a->pos != e->args)
904                         return NULL;
905                 return a->n == 0 ? ast_strdup("all") : ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
906         }
907         /* 'core set debug channel {all|chan_id}' */
908         if (a->argc == e->args + 2) {
909                 if (!strcasecmp(a->argv[e->args + 1], "off"))
910                         is_off = 1;
911                 else
912                         return CLI_SHOWUSAGE;
913         } else if (a->argc != e->args + 1)
914                 return CLI_SHOWUSAGE;
915
916         is_all = !strcasecmp("all", a->argv[e->args]);
917         if (is_all) {
918                 if (is_off) {
919                         global_fin &= ~DEBUGCHAN_FLAG;
920                         global_fout &= ~DEBUGCHAN_FLAG;
921                 } else {
922                         global_fin |= DEBUGCHAN_FLAG;
923                         global_fout |= DEBUGCHAN_FLAG;
924                 }
925                 c = ast_channel_walk_locked(NULL);
926         } else {
927                 c = ast_get_channel_by_name_locked(a->argv[e->args]);
928                 if (c == NULL)
929                         ast_cli(a->fd, "No such channel %s\n", a->argv[e->args]);
930         }
931         while (c) {
932                 if (!(c->fin & DEBUGCHAN_FLAG) || !(c->fout & DEBUGCHAN_FLAG)) {
933                         if (is_off) {
934                                 c->fin &= ~DEBUGCHAN_FLAG;
935                                 c->fout &= ~DEBUGCHAN_FLAG;
936                         } else {
937                                 c->fin |= DEBUGCHAN_FLAG;
938                                 c->fout |= DEBUGCHAN_FLAG;
939                         }
940                         ast_cli(a->fd, "Debugging %s on channel %s\n", is_off ? "disabled" : "enabled", c->name);
941                 }
942                 ast_channel_unlock(c);
943                 if (!is_all)
944                         break;
945                 c = ast_channel_walk_locked(c);
946         }
947         ast_cli(a->fd, "Debugging on new channels is %s\n", is_off ? "disabled" : "enabled");
948         return CLI_SUCCESS;
949 }
950
951 static char *handle_debugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
952 {
953         char *res;
954
955         if (cmd == CLI_HANDLER && a->argc != e->args + 1)
956                 return CLI_SHOWUSAGE;
957         res = handle_core_set_debug_channel(e, cmd, a);
958         if (cmd == CLI_INIT)
959                 e->command = "debug channel";
960         return res;
961 }
962
963 static char *handle_nodebugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
964 {
965         char *res;
966         if (cmd == CLI_HANDLER) {
967                 if (a->argc != e->args + 1)
968                         return CLI_SHOWUSAGE;
969                 /* pretend we have an extra "off" at the end. We can do this as the array
970                  * is NULL terminated so we overwrite that entry.
971                  */
972                 a->argv[e->args+1] = "off";
973                 a->argc++;
974         }
975         res = handle_core_set_debug_channel(e, cmd, a);
976         if (cmd == CLI_INIT)
977                 e->command = "no debug channel";
978         return res;
979 }
980                 
981 static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
982 {
983         struct ast_channel *c=NULL;
984         struct timeval now;
985         struct ast_str *out = ast_str_alloca(2048);
986         char cdrtime[256];
987         char nf[256], wf[256], rf[256];
988         long elapsed_seconds=0;
989         int hour=0, min=0, sec=0;
990 #ifdef CHANNEL_TRACE
991         int trace_enabled;
992 #endif
993
994         switch (cmd) {
995         case CLI_INIT:
996                 e->command = "core show channel";
997                 e->usage = 
998                         "Usage: core show channel <channel>\n"
999                         "       Shows lots of information about the specified channel.\n";
1000                 return NULL;
1001         case CLI_GENERATE:
1002                 return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
1003         }
1004         
1005         if (a->argc != 4)
1006                 return CLI_SHOWUSAGE;
1007         now = ast_tvnow();
1008         c = ast_get_channel_by_name_locked(a->argv[3]);
1009         if (!c) {
1010                 ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
1011                 return CLI_SUCCESS;
1012         }
1013         if (c->cdr) {
1014                 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
1015                 hour = elapsed_seconds / 3600;
1016                 min = (elapsed_seconds % 3600) / 60;
1017                 sec = elapsed_seconds % 60;
1018                 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
1019         } else
1020                 strcpy(cdrtime, "N/A");
1021         ast_cli(a->fd, 
1022                 " -- General --\n"
1023                 "           Name: %s\n"
1024                 "           Type: %s\n"
1025                 "       UniqueID: %s\n"
1026                 "      Caller ID: %s\n"
1027                 " Caller ID Name: %s\n"
1028                 "    DNID Digits: %s\n"
1029                 "       Language: %s\n"
1030                 "          State: %s (%d)\n"
1031                 "          Rings: %d\n"
1032                 "  NativeFormats: %s\n"
1033                 "    WriteFormat: %s\n"
1034                 "     ReadFormat: %s\n"
1035                 " WriteTranscode: %s\n"
1036                 "  ReadTranscode: %s\n"
1037                 "1st File Descriptor: %d\n"
1038                 "      Frames in: %d%s\n"
1039                 "     Frames out: %d%s\n"
1040                 " Time to Hangup: %ld\n"
1041                 "   Elapsed Time: %s\n"
1042                 "  Direct Bridge: %s\n"
1043                 "Indirect Bridge: %s\n"
1044                 " --   PBX   --\n"
1045                 "        Context: %s\n"
1046                 "      Extension: %s\n"
1047                 "       Priority: %d\n"
1048                 "     Call Group: %llu\n"
1049                 "   Pickup Group: %llu\n"
1050                 "    Application: %s\n"
1051                 "           Data: %s\n"
1052                 "    Blocking in: %s\n",
1053                 c->name, c->tech->type, c->uniqueid,
1054                 S_OR(c->cid.cid_num, "(N/A)"),
1055                 S_OR(c->cid.cid_name, "(N/A)"),
1056                 S_OR(c->cid.cid_dnid, "(N/A)"), 
1057                 c->language,    
1058                 ast_state2str(c->_state), c->_state, c->rings, 
1059                 ast_getformatname_multiple(nf, sizeof(nf), c->nativeformats), 
1060                 ast_getformatname_multiple(wf, sizeof(wf), c->writeformat), 
1061                 ast_getformatname_multiple(rf, sizeof(rf), c->readformat),
1062                 c->writetrans ? "Yes" : "No",
1063                 c->readtrans ? "Yes" : "No",
1064                 c->fds[0],
1065                 c->fin & ~DEBUGCHAN_FLAG, (c->fin & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
1066                 c->fout & ~DEBUGCHAN_FLAG, (c->fout & DEBUGCHAN_FLAG) ? " (DEBUGGED)" : "",
1067                 (long)c->whentohangup.tv_sec,
1068                 cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>", 
1069                 c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
1070                 ( c-> data ? S_OR(c->data, "(Empty)") : "(None)"),
1071                 (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
1072         
1073         if (pbx_builtin_serialize_variables(c, &out))
1074                 ast_cli(a->fd,"      Variables:\n%s\n", out->str);
1075         if (c->cdr && ast_cdr_serialize_variables(c->cdr, &out, '=', '\n', 1))
1076                 ast_cli(a->fd,"  CDR Variables:\n%s\n", out->str);
1077 #ifdef CHANNEL_TRACE
1078         trace_enabled = ast_channel_trace_is_enabled(c);
1079         ast_cli(a->fd, "  Context Trace: %s\n", trace_enabled ? "Enabled" : "Disabled");
1080         if (trace_enabled && ast_channel_trace_serialize(c, &out))
1081                 ast_cli(a->fd, "          Trace:\n%s\n", out->str);
1082 #endif
1083         ast_channel_unlock(c);
1084         return CLI_SUCCESS;
1085 }
1086
1087 /*
1088  * helper function to generate CLI matches from a fixed set of values.
1089  * A NULL word is acceptable.
1090  */
1091 char *ast_cli_complete(const char *word, char *const choices[], int state)
1092 {
1093         int i, which = 0, len;
1094         len = ast_strlen_zero(word) ? 0 : strlen(word);
1095
1096         for (i = 0; choices[i]; i++) {
1097                 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
1098                         return ast_strdup(choices[i]);
1099         }
1100         return NULL;
1101 }
1102
1103 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
1104 {
1105         struct ast_channel *c = NULL;
1106         int which = 0;
1107         int wordlen;
1108         char notfound = '\0';
1109         char *ret = &notfound; /* so NULL can break the loop */
1110
1111         if (pos != rpos)
1112                 return NULL;
1113
1114         wordlen = strlen(word); 
1115
1116         while (ret == &notfound && (c = ast_channel_walk_locked(c))) {
1117                 if (!strncasecmp(word, c->name, wordlen) && ++which > state)
1118                         ret = ast_strdup(c->name);
1119                 ast_channel_unlock(c);
1120         }
1121         return ret == &notfound ? NULL : ret;
1122 }
1123
1124 static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1125 {
1126 #define FORMAT_STRING  "%-25s  %-20s  %-20s\n"
1127
1128         struct ast_group_info *gi = NULL;
1129         int numchans = 0;
1130         regex_t regexbuf;
1131         int havepattern = 0;
1132
1133         switch (cmd) {
1134         case CLI_INIT:
1135                 e->command = "group show channels";
1136                 e->usage = 
1137                         "Usage: group show channels [pattern]\n"
1138                         "       Lists all currently active channels with channel group(s) specified.\n"
1139                         "       Optional regular expression pattern is matched to group names for each\n"
1140                         "       channel.\n";
1141                 return NULL;
1142         case CLI_GENERATE:
1143                 return NULL;
1144         }
1145
1146         if (a->argc < 3 || a->argc > 4)
1147                 return CLI_SHOWUSAGE;
1148         
1149         if (a->argc == 4) {
1150                 if (regcomp(&regexbuf, a->argv[3], REG_EXTENDED | REG_NOSUB))
1151                         return CLI_SHOWUSAGE;
1152                 havepattern = 1;
1153         }
1154
1155         ast_cli(a->fd, FORMAT_STRING, "Channel", "Group", "Category");
1156
1157         ast_app_group_list_rdlock();
1158         
1159         gi = ast_app_group_list_head();
1160         while (gi) {
1161                 if (!havepattern || !regexec(&regexbuf, gi->group, 0, NULL, 0)) {
1162                         ast_cli(a->fd, FORMAT_STRING, gi->chan->name, gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category));
1163                         numchans++;
1164                 }
1165                 gi = AST_LIST_NEXT(gi, list);
1166         }
1167         
1168         ast_app_group_list_unlock();
1169         
1170         if (havepattern)
1171                 regfree(&regexbuf);
1172
1173         ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
1174         return CLI_SUCCESS;
1175 #undef FORMAT_STRING
1176 }
1177
1178 static struct ast_cli_entry cli_debug_channel_deprecated = AST_CLI_DEFINE(handle_debugchan_deprecated, "Enable debugging on channel");
1179 static struct ast_cli_entry cli_module_load_deprecated = AST_CLI_DEFINE(handle_load_deprecated, "Load a module");
1180 static struct ast_cli_entry cli_module_reload_deprecated = AST_CLI_DEFINE(handle_reload_deprecated, "reload modules by name");
1181 static struct ast_cli_entry cli_module_unload_deprecated = AST_CLI_DEFINE(handle_unload_deprecated, "unload modules by name");
1182
1183 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1184
1185 static struct ast_cli_entry cli_cli[] = {
1186         /* Deprecated, but preferred command is now consolidated (and already has a deprecated command for it). */
1187         AST_CLI_DEFINE(handle_commandcomplete, "Command complete"),
1188         AST_CLI_DEFINE(handle_commandnummatches, "Returns number of command matches"),
1189         AST_CLI_DEFINE(handle_commandmatchesarray, "Returns command matches array"),
1190
1191         AST_CLI_DEFINE(handle_nodebugchan_deprecated, "Disable debugging on channel(s)"),
1192
1193         AST_CLI_DEFINE(handle_chanlist, "Display information on channels"),
1194
1195         AST_CLI_DEFINE(handle_showcalls, "Display information on calls"),
1196
1197         AST_CLI_DEFINE(handle_showchan, "Display information on a specific channel"),
1198
1199         AST_CLI_DEFINE(handle_core_set_debug_channel, "Enable/disable debugging on a channel",
1200                 .deprecate_cmd = &cli_debug_channel_deprecated),
1201
1202         AST_CLI_DEFINE(handle_verbose, "Set level of debug/verbose chattiness"),
1203
1204         AST_CLI_DEFINE(group_show_channels, "Display active channels with group(s)"),
1205
1206         AST_CLI_DEFINE(handle_help, "Display help list, or specific help on a command"),
1207
1208         AST_CLI_DEFINE(handle_logger_mute, "Toggle logging output to a console"),
1209
1210         AST_CLI_DEFINE(handle_modlist, "List modules and info"),
1211
1212         AST_CLI_DEFINE(handle_load, "Load a module by name", .deprecate_cmd = &cli_module_load_deprecated),
1213
1214         AST_CLI_DEFINE(handle_reload, "Reload configuration", .deprecate_cmd = &cli_module_reload_deprecated),
1215
1216         AST_CLI_DEFINE(handle_unload, "Unload a module by name", .deprecate_cmd = &cli_module_unload_deprecated ),
1217
1218         AST_CLI_DEFINE(handle_showuptime, "Show uptime information"),
1219
1220         AST_CLI_DEFINE(handle_softhangup, "Request a hangup on a given channel"),
1221 };
1222
1223 /*!
1224  * Some regexp characters in cli arguments are reserved and used as separators.
1225  */
1226 static const char cli_rsvd[] = "[]{}|*%";
1227
1228 /*!
1229  * initialize the _full_cmd string and related parameters,
1230  * return 0 on success, -1 on error.
1231  */
1232 static int set_full_cmd(struct ast_cli_entry *e)
1233 {
1234         int i;
1235         char buf[80];
1236
1237         ast_join(buf, sizeof(buf), e->cmda);
1238         e->_full_cmd = ast_strdup(buf);
1239         if (!e->_full_cmd) {
1240                 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
1241                 return -1;
1242         }
1243         e->cmdlen = strcspn(e->_full_cmd, cli_rsvd);
1244         for (i = 0; e->cmda[i]; i++)
1245                 ;
1246         e->args = i;
1247         return 0;
1248 }
1249
1250 /*! \brief initialize the _full_cmd string in * each of the builtins. */
1251 void ast_builtins_init(void)
1252 {
1253         ast_cli_register_multiple(cli_cli, sizeof(cli_cli) / sizeof(struct ast_cli_entry));
1254 }
1255
1256 static struct ast_cli_entry *cli_next(struct ast_cli_entry *e)
1257 {
1258         if (e) {
1259                 return AST_LIST_NEXT(e, list);
1260         } else {
1261                 return AST_LIST_FIRST(&helpers);
1262         }
1263 }
1264
1265 /*!
1266  * match a word in the CLI entry.
1267  * returns -1 on mismatch, 0 on match of an optional word,
1268  * 1 on match of a full word.
1269  *
1270  * The pattern can be
1271  *   any_word           match for equal
1272  *   [foo|bar|baz]      optionally, one of these words
1273  *   {foo|bar|baz}      exactly, one of these words
1274  *   %                  any word
1275  */
1276 static int word_match(const char *cmd, const char *cli_word)
1277 {
1278         int l;
1279         char *pos;
1280
1281         if (ast_strlen_zero(cmd) || ast_strlen_zero(cli_word))
1282                 return -1;
1283         if (!strchr(cli_rsvd, cli_word[0])) /* normal match */
1284                 return (strcasecmp(cmd, cli_word) == 0) ? 1 : -1;
1285         /* regexp match, takes [foo|bar] or {foo|bar} */
1286         l = strlen(cmd);
1287         /* wildcard match - will extend in the future */
1288         if (l > 0 && cli_word[0] == '%') {
1289                 return 1;       /* wildcard */
1290         }
1291         pos = strcasestr(cli_word, cmd);
1292         if (pos == NULL) /* not found, say ok if optional */
1293                 return cli_word[0] == '[' ? 0 : -1;
1294         if (pos == cli_word)    /* no valid match at the beginning */
1295                 return -1;
1296         if (strchr(cli_rsvd, pos[-1]) && strchr(cli_rsvd, pos[l]))
1297                 return 1;       /* valid match */
1298         return -1;      /* not found */
1299 }
1300
1301 /*! \brief if word is a valid prefix for token, returns the pos-th
1302  * match as a malloced string, or NULL otherwise.
1303  * Always tell in *actual how many matches we got.
1304  */
1305 static char *is_prefix(const char *word, const char *token,
1306         int pos, int *actual)
1307 {
1308         int lw;
1309         char *s, *t1;
1310
1311         *actual = 0;
1312         if (ast_strlen_zero(token))
1313                 return NULL;
1314         if (ast_strlen_zero(word))
1315                 word = "";      /* dummy */
1316         lw = strlen(word);
1317         if (strcspn(word, cli_rsvd) != lw)
1318                 return NULL;    /* no match if word has reserved chars */
1319         if (strchr(cli_rsvd, token[0]) == NULL) {       /* regular match */
1320                 if (strncasecmp(token, word, lw))       /* no match */
1321                         return NULL;
1322                 *actual = 1;
1323                 return (pos != 0) ? NULL : ast_strdup(token);
1324         }
1325         /* now handle regexp match */
1326
1327         /* Wildcard always matches, so we never do is_prefix on them */
1328
1329         t1 = ast_strdupa(token + 1);    /* copy, skipping first char */
1330         while (pos >= 0 && (s = strsep(&t1, cli_rsvd)) && *s) {
1331                 if (*s == '%')  /* wildcard */
1332                         continue;
1333                 if (strncasecmp(s, word, lw))   /* no match */
1334                         continue;
1335                 (*actual)++;
1336                 if (pos-- == 0)
1337                         return ast_strdup(s);
1338         }
1339         return NULL;
1340 }
1341
1342 /*!
1343  * \brief locate a cli command in the 'helpers' list (which must be locked).
1344  * exact has 3 values:
1345  *      0       returns if the search key is equal or longer than the entry.
1346  *              note that trailing optional arguments are skipped.
1347  *      -1      true if the mismatch is on the last word XXX not true!
1348  *      1       true only on complete, exact match.
1349  *
1350  * The search compares word by word taking care of regexps in e->cmda
1351  */
1352 static struct ast_cli_entry *find_cli(char *const cmds[], int match_type)
1353 {
1354         int matchlen = -1;      /* length of longest match so far */
1355         struct ast_cli_entry *cand = NULL, *e=NULL;
1356
1357         while ( (e = cli_next(e)) ) {
1358                 /* word-by word regexp comparison */
1359                 char * const *src = cmds;
1360                 char * const *dst = e->cmda;
1361                 int n = 0;
1362                 for (;; dst++, src += n) {
1363                         n = word_match(*src, *dst);
1364                         if (n < 0)
1365                                 break;
1366                 }
1367                 if (ast_strlen_zero(*dst) || ((*dst)[0] == '[' && ast_strlen_zero(dst[1]))) {
1368                         /* no more words in 'e' */
1369                         if (ast_strlen_zero(*src))      /* exact match, cannot do better */
1370                                 break;
1371                         /* Here, cmds has more words than the entry 'e' */
1372                         if (match_type != 0)    /* but we look for almost exact match... */
1373                                 continue;       /* so we skip this one. */
1374                         /* otherwise we like it (case 0) */
1375                 } else {        /* still words in 'e' */
1376                         if (ast_strlen_zero(*src))
1377                                 continue; /* cmds is shorter than 'e', not good */
1378                         /* Here we have leftover words in cmds and 'e',
1379                          * but there is a mismatch. We only accept this one if match_type == -1
1380                          * and this is the last word for both.
1381                          */
1382                         if (match_type != -1 || !ast_strlen_zero(src[1]) ||
1383                             !ast_strlen_zero(dst[1]))   /* not the one we look for */
1384                                 continue;
1385                         /* good, we are in case match_type == -1 and mismatch on last word */
1386                 }
1387                 if (src - cmds > matchlen) {    /* remember the candidate */
1388                         matchlen = src - cmds;
1389                         cand = e;
1390                 }
1391         }
1392         return e ? e : cand;
1393 }
1394
1395 static char *find_best(char *argv[])
1396 {
1397         static char cmdline[80];
1398         int x;
1399         /* See how close we get, then print the candidate */
1400         char *myargv[AST_MAX_CMD_LEN];
1401         for (x=0;x<AST_MAX_CMD_LEN;x++)
1402                 myargv[x]=NULL;
1403         AST_RWLIST_RDLOCK(&helpers);
1404         for (x=0;argv[x];x++) {
1405                 myargv[x] = argv[x];
1406                 if (!find_cli(myargv, -1))
1407                         break;
1408         }
1409         AST_RWLIST_UNLOCK(&helpers);
1410         ast_join(cmdline, sizeof(cmdline), myargv);
1411         return cmdline;
1412 }
1413
1414 static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1415 {
1416         if (e->deprecate_cmd) {
1417                 __ast_cli_unregister(e->deprecate_cmd, e);
1418         }
1419         if (e->inuse) {
1420                 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
1421         } else {
1422                 AST_RWLIST_WRLOCK(&helpers);
1423                 AST_RWLIST_REMOVE(&helpers, e, list);
1424                 AST_RWLIST_UNLOCK(&helpers);
1425                 ast_free(e->_full_cmd);
1426                 e->_full_cmd = NULL;
1427                 if (e->handler) {
1428                         /* this is a new-style entry. Reset fields and free memory. */
1429                         bzero((char **)(e->cmda), sizeof(e->cmda));
1430                         ast_free(e->command);
1431                         e->command = NULL;
1432                         e->usage = NULL;
1433                 }
1434         }
1435         return 0;
1436 }
1437
1438 static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
1439 {
1440         struct ast_cli_entry *cur;
1441         int i, lf, ret = -1;
1442
1443         struct ast_cli_args a;  /* fake argument */
1444         char **dst = (char **)e->cmda;  /* need to cast as the entry is readonly */
1445         char *s;
1446
1447         bzero (&a, sizeof(a));
1448         e->handler(e, CLI_INIT, &a);
1449         /* XXX check that usage and command are filled up */
1450         s = ast_skip_blanks(e->command);
1451         s = e->command = ast_strdup(s);
1452         for (i=0; !ast_strlen_zero(s) && i < AST_MAX_CMD_LEN-1; i++) {
1453                 *dst++ = s;     /* store string */
1454                 s = ast_skip_nonblanks(s);
1455                 if (*s == '\0') /* we are done */
1456                         break;
1457                 *s++ = '\0';
1458                 s = ast_skip_blanks(s);
1459         }
1460         *dst++ = NULL;
1461         
1462         AST_RWLIST_WRLOCK(&helpers);
1463         
1464         if (find_cli(e->cmda, 1)) {
1465                 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", e->_full_cmd);
1466                 goto done;
1467         }
1468         if (set_full_cmd(e))
1469                 goto done;
1470         if (!ed) {
1471                 e->deprecated = 0;
1472         } else {
1473                 e->deprecated = 1;
1474                 e->summary = ed->summary;
1475                 e->usage = ed->usage;
1476                 /* XXX If command A deprecates command B, and command B deprecates command C...
1477                    Do we want to show command A or command B when telling the user to use new syntax?
1478                    This currently would show command A.
1479                    To show command B, you just need to always use ed->_full_cmd.
1480                  */
1481                 e->_deprecated_by = S_OR(ed->_deprecated_by, ed->_full_cmd);
1482         }
1483
1484         lf = e->cmdlen;
1485         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
1486                 int len = cur->cmdlen;
1487                 if (lf < len)
1488                         len = lf;
1489                 if (strncasecmp(e->_full_cmd, cur->_full_cmd, len) < 0) {
1490                         AST_RWLIST_INSERT_BEFORE_CURRENT(e, list); 
1491                         break;
1492                 }
1493         }
1494         AST_RWLIST_TRAVERSE_SAFE_END;
1495
1496         if (!cur)
1497                 AST_RWLIST_INSERT_TAIL(&helpers, e, list); 
1498         ret = 0;        /* success */
1499
1500 done:
1501         AST_RWLIST_UNLOCK(&helpers);
1502
1503         if (e->deprecate_cmd) {
1504                 /* This command deprecates another command.  Register that one also. */
1505                 __ast_cli_register(e->deprecate_cmd, e);
1506         }
1507         
1508         return ret;
1509 }
1510
1511 /* wrapper function, so we can unregister deprecated commands recursively */
1512 int ast_cli_unregister(struct ast_cli_entry *e)
1513 {
1514         return __ast_cli_unregister(e, NULL);
1515 }
1516
1517 /* wrapper function, so we can register deprecated commands recursively */
1518 int ast_cli_register(struct ast_cli_entry *e)
1519 {
1520         return __ast_cli_register(e, NULL);
1521 }
1522
1523 /*
1524  * register/unregister an array of entries.
1525  */
1526 int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
1527 {
1528         int i, res = 0;
1529
1530         for (i = 0; i < len; i++)
1531                 res |= ast_cli_register(e + i);
1532
1533         return res;
1534 }
1535
1536 int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
1537 {
1538         int i, res = 0;
1539
1540         for (i = 0; i < len; i++)
1541                 res |= ast_cli_unregister(e + i);
1542
1543         return res;
1544 }
1545
1546
1547 /*! \brief helper for final part of handle_help
1548  *  if locked = 1, assume the list is already locked
1549  */
1550 static char *help1(int fd, char *match[], int locked)
1551 {
1552         char matchstr[80] = "";
1553         struct ast_cli_entry *e = NULL;
1554         int len = 0;
1555         int found = 0;
1556
1557         if (match) {
1558                 ast_join(matchstr, sizeof(matchstr), match);
1559                 len = strlen(matchstr);
1560         }
1561         if (!locked)
1562                 AST_RWLIST_RDLOCK(&helpers);
1563         while ( (e = cli_next(e)) ) {
1564                 /* Hide commands that start with '_' */
1565                 if (e->_full_cmd[0] == '_')
1566                         continue;
1567                 /* Hide commands that are marked as deprecated. */
1568                 if (e->deprecated)
1569                         continue;
1570                 if (match && strncasecmp(matchstr, e->_full_cmd, len))
1571                         continue;
1572                 ast_cli(fd, "%30.30s %s\n", e->_full_cmd, S_OR(e->summary, "<no description available>"));
1573                 found++;
1574         }
1575         if (!locked)
1576                 AST_RWLIST_UNLOCK(&helpers);
1577         if (!found && matchstr[0])
1578                 ast_cli(fd, "No such command '%s'.\n", matchstr);
1579         return CLI_SUCCESS;
1580 }
1581
1582 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1583 {
1584         char fullcmd[80];
1585         struct ast_cli_entry *my_e;
1586         char *res = CLI_SUCCESS;
1587
1588         if (cmd == CLI_INIT) {
1589                 e->command = "help";
1590                 e->usage =
1591                         "Usage: help [topic]\n"
1592                         "       When called with a topic as an argument, displays usage\n"
1593                         "       information on the given command. If called without a\n"
1594                         "       topic, it provides a list of commands.\n";
1595                 return NULL;
1596
1597         } else if (cmd == CLI_GENERATE) {
1598                 /* skip first 4 or 5 chars, "help " */
1599                 int l = strlen(a->line);
1600
1601                 if (l > 5)
1602                         l = 5;
1603                 /* XXX watch out, should stop to the non-generator parts */
1604                 return __ast_cli_generator(a->line + l, a->word, a->n, 0);
1605         }
1606         if (a->argc == 1)
1607                 return help1(a->fd, NULL, 0);
1608
1609         AST_RWLIST_RDLOCK(&helpers);
1610         my_e = find_cli(a->argv + 1, 1);        /* try exact match first */
1611         if (!my_e) {
1612                 res = help1(a->fd, a->argv + 1, 1 /* locked */);
1613                 AST_RWLIST_UNLOCK(&helpers);
1614                 return res;
1615         }
1616         if (my_e->usage)
1617                 ast_cli(a->fd, "%s", my_e->usage);
1618         else {
1619                 ast_join(fullcmd, sizeof(fullcmd), a->argv+1);
1620                 ast_cli(a->fd, "No help text available for '%s'.\n", fullcmd);
1621         }
1622         AST_RWLIST_UNLOCK(&helpers);
1623         return res;
1624 }
1625
1626 static char *parse_args(const char *s, int *argc, char *argv[], int max, int *trailingwhitespace)
1627 {
1628         char *duplicate, *cur;
1629         int x = 0;
1630         int quoted = 0;
1631         int escaped = 0;
1632         int whitespace = 1;
1633         int dummy = 0;
1634
1635         if (trailingwhitespace == NULL)
1636                 trailingwhitespace = &dummy;
1637         *trailingwhitespace = 0;
1638         if (s == NULL)  /* invalid, though! */
1639                 return NULL;
1640         /* make a copy to store the parsed string */
1641         if (!(duplicate = ast_strdup(s)))
1642                 return NULL;
1643
1644         cur = duplicate;
1645         /* scan the original string copying into cur when needed */
1646         for (; *s ; s++) {
1647                 if (x >= max - 1) {
1648                         ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
1649                         break;
1650                 }
1651                 if (*s == '"' && !escaped) {
1652                         quoted = !quoted;
1653                         if (quoted && whitespace) {
1654                                 /* start a quoted string from previous whitespace: new argument */
1655                                 argv[x++] = cur;
1656                                 whitespace = 0;
1657                         }
1658                 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
1659                         /* If we are not already in whitespace, and not in a quoted string or
1660                            processing an escape sequence, and just entered whitespace, then
1661                            finalize the previous argument and remember that we are in whitespace
1662                         */
1663                         if (!whitespace) {
1664                                 *cur++ = '\0';
1665                                 whitespace = 1;
1666                         }
1667                 } else if (*s == '\\' && !escaped) {
1668                         escaped = 1;
1669                 } else {
1670                         if (whitespace) {
1671                                 /* we leave whitespace, and are not quoted. So it's a new argument */
1672                                 argv[x++] = cur;
1673                                 whitespace = 0;
1674                         }
1675                         *cur++ = *s;
1676                         escaped = 0;
1677                 }
1678         }
1679         /* Null terminate */
1680         *cur++ = '\0';
1681         /* XXX put a NULL in the last argument, because some functions that take
1682          * the array may want a null-terminated array.
1683          * argc still reflects the number of non-NULL entries.
1684          */
1685         argv[x] = NULL;
1686         *argc = x;
1687         *trailingwhitespace = whitespace;
1688         return duplicate;
1689 }
1690
1691 /*! \brief Return the number of unique matches for the generator */
1692 int ast_cli_generatornummatches(const char *text, const char *word)
1693 {
1694         int matches = 0, i = 0;
1695         char *buf = NULL, *oldbuf = NULL;
1696
1697         while ((buf = ast_cli_generator(text, word, i++))) {
1698                 if (!oldbuf || strcmp(buf,oldbuf))
1699                         matches++;
1700                 if (oldbuf)
1701                         ast_free(oldbuf);
1702                 oldbuf = buf;
1703         }
1704         if (oldbuf)
1705                 ast_free(oldbuf);
1706         return matches;
1707 }
1708
1709 char **ast_cli_completion_matches(const char *text, const char *word)
1710 {
1711         char **match_list = NULL, *retstr, *prevstr;
1712         size_t match_list_len, max_equal, which, i;
1713         int matches = 0;
1714
1715         /* leave entry 0 free for the longest common substring */
1716         match_list_len = 1;
1717         while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1718                 if (matches + 1 >= match_list_len) {
1719                         match_list_len <<= 1;
1720                         if (!(match_list = ast_realloc(match_list, match_list_len * sizeof(*match_list))))
1721                                 return NULL;
1722                 }
1723                 match_list[++matches] = retstr;
1724         }
1725
1726         if (!match_list)
1727                 return match_list; /* NULL */
1728
1729         /* Find the longest substring that is common to all results
1730          * (it is a candidate for completion), and store a copy in entry 0.
1731          */
1732         prevstr = match_list[1];
1733         max_equal = strlen(prevstr);
1734         for (which = 2; which <= matches; which++) {
1735                 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1736                         continue;
1737                 max_equal = i;
1738         }
1739
1740         if (!(retstr = ast_malloc(max_equal + 1)))
1741                 return NULL;
1742         
1743         ast_copy_string(retstr, match_list[1], max_equal + 1);
1744         match_list[0] = retstr;
1745
1746         /* ensure that the array is NULL terminated */
1747         if (matches + 1 >= match_list_len) {
1748                 if (!(match_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list))))
1749                         return NULL;
1750         }
1751         match_list[matches + 1] = NULL;
1752
1753         return match_list;
1754 }
1755
1756 /*! \brief returns true if there are more words to match */
1757 static int more_words (char * const *dst)
1758 {
1759         int i;
1760         for (i = 0; dst[i]; i++) {
1761                 if (dst[i][0] != '[')
1762                         return -1;
1763         }
1764         return 0;
1765 }
1766         
1767 /*
1768  * generate the entry at position 'state'
1769  */
1770 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
1771 {
1772         char *argv[AST_MAX_ARGS];
1773         struct ast_cli_entry *e = NULL;
1774         int x = 0, argindex, matchlen;
1775         int matchnum=0;
1776         char *ret = NULL;
1777         char matchstr[80] = "";
1778         int tws = 0;
1779         /* Split the argument into an array of words */
1780         char *duplicate = parse_args(text, &x, argv, ARRAY_LEN(argv), &tws);
1781
1782         if (!duplicate) /* malloc error */
1783                 return NULL;
1784
1785         /* Compute the index of the last argument (could be an empty string) */
1786         argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
1787
1788         /* rebuild the command, ignore terminating white space and flatten space */
1789         ast_join(matchstr, sizeof(matchstr)-1, argv);
1790         matchlen = strlen(matchstr);
1791         if (tws) {
1792                 strcat(matchstr, " "); /* XXX */
1793                 if (matchlen)
1794                         matchlen++;
1795         }
1796         if (lock)
1797                 AST_RWLIST_RDLOCK(&helpers);
1798         while ( (e = cli_next(e)) ) {
1799                 /* XXX repeated code */
1800                 int src = 0, dst = 0, n = 0;
1801
1802                 if (e->command[0] == '_')
1803                         continue;
1804
1805                 /*
1806                  * Try to match words, up to and excluding the last word, which
1807                  * is either a blank or something that we want to extend.
1808                  */
1809                 for (;src < argindex; dst++, src += n) {
1810                         n = word_match(argv[src], e->cmda[dst]);
1811                         if (n < 0)
1812                                 break;
1813                 }
1814
1815                 if (src != argindex && more_words(e->cmda + dst))       /* not a match */
1816                         continue;
1817                 ret = is_prefix(argv[src], e->cmda[dst], state - matchnum, &n);
1818                 matchnum += n;  /* this many matches here */
1819                 if (ret) {
1820                         /*
1821                          * argv[src] is a valid prefix of the next word in this
1822                          * command. If this is also the correct entry, return it.
1823                          */
1824                         if (matchnum > state)
1825                                 break;
1826                         ast_free(ret);
1827                         ret = NULL;
1828                 } else if (ast_strlen_zero(e->cmda[dst])) {
1829                         /*
1830                          * This entry is a prefix of the command string entered
1831                          * (only one entry in the list should have this property).
1832                          * Run the generator if one is available. In any case we are done.
1833                          */
1834                         if (e->handler) {       /* new style command */
1835                                 struct ast_cli_args a = {
1836                                         .line = matchstr, .word = word,
1837                                         .pos = argindex,
1838                                         .n = state - matchnum,
1839                                         .argv = argv,
1840                                         .argc = x};
1841                                 ret = e->handler(e, CLI_GENERATE, &a);
1842                         }
1843                         if (ret)
1844                                 break;
1845                 }
1846         }
1847         if (lock)
1848                 AST_RWLIST_UNLOCK(&helpers);
1849         ast_free(duplicate);
1850         return ret;
1851 }
1852
1853 char *ast_cli_generator(const char *text, const char *word, int state)
1854 {
1855         return __ast_cli_generator(text, word, state, 1);
1856 }
1857
1858 int ast_cli_command(int fd, const char *s)
1859 {
1860         char *args[AST_MAX_ARGS + 1];
1861         struct ast_cli_entry *e;
1862         int x;
1863         char *duplicate = parse_args(s, &x, args + 1, AST_MAX_ARGS, NULL);
1864         char *retval = NULL;
1865         struct ast_cli_args a = {
1866                 .fd = fd, .argc = x, .argv = args+1 };
1867
1868         if (duplicate == NULL)
1869                 return -1;
1870
1871         if (x < 1)      /* We need at least one entry, otherwise ignore */
1872                 goto done;
1873
1874         AST_RWLIST_RDLOCK(&helpers);
1875         e = find_cli(args + 1, 0);
1876         if (e)
1877                 ast_atomic_fetchadd_int(&e->inuse, 1);
1878         AST_RWLIST_UNLOCK(&helpers);
1879         if (e == NULL) {
1880                 ast_cli(fd, "No such command '%s' (type 'help %s' for other possible commands)\n", s, find_best(args + 1));
1881                 goto done;
1882         }
1883         /*
1884          * Within the handler, argv[-1] contains a pointer to the ast_cli_entry.
1885          * Remember that the array returned by parse_args is NULL-terminated.
1886          */
1887         args[0] = (char *)e;
1888
1889         retval = e->handler(e, CLI_HANDLER, &a);
1890
1891         if (retval == CLI_SHOWUSAGE) {
1892                 ast_cli(fd, "%s", S_OR(e->usage, "Invalid usage, but no usage information available.\n"));
1893                 AST_RWLIST_RDLOCK(&helpers);
1894                 if (e->deprecated)
1895                         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);
1896                 AST_RWLIST_UNLOCK(&helpers);
1897         } else {
1898                 if (retval == CLI_FAILURE)
1899                         ast_cli(fd, "Command '%s' failed.\n", s);
1900                 AST_RWLIST_RDLOCK(&helpers);
1901                 if (e->deprecated == 1) {
1902                         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);
1903                         e->deprecated = 2;
1904                 }
1905                 AST_RWLIST_UNLOCK(&helpers);
1906         }
1907         ast_atomic_fetchadd_int(&e->inuse, -1);
1908 done:
1909         ast_free(duplicate);
1910         return 0;
1911 }
1912
1913 int ast_cli_command_multiple(int fd, size_t size, const char *s)
1914 {
1915         char cmd[512];
1916         int x, y = 0, count = 0;
1917
1918         for (x = 0; x < size; x++) {
1919                 cmd[y] = s[x];
1920                 y++;
1921                 if (s[x] == '\0') {
1922                         ast_cli_command(fd, cmd);
1923                         y = 0;
1924                         count++;
1925                 }
1926         }
1927         return count;
1928 }