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