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