Minor CLI fix
[asterisk/asterisk.git] / cli.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Standard Command Line Interface
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <unistd.h>
15 #include <stdlib.h>
16 #include <asterisk/logger.h>
17 #include <asterisk/options.h>
18 #include <asterisk/cli.h>
19 #include <asterisk/module.h>
20 #include <asterisk/channel.h>
21 #include <asterisk/channel_pvt.h>
22 #include <sys/signal.h>
23 #include <stdio.h>
24 #include <signal.h>
25 #include <string.h>
26 #include <pthread.h>
27 /* For rl_filename_completion */
28 #include "editline/readline/readline.h"
29 /* For module directory */
30 #include "asterisk.h"
31 #include "build.h"
32 #include "astconf.h"
33
34 #define VERSION_INFO "Asterisk " ASTERISK_VERSION " built by " BUILD_USER "@" BUILD_HOSTNAME \
35         " on a " BUILD_MACHINE " running " BUILD_OS
36         
37 void ast_cli(int fd, char *fmt, ...)
38 {
39         char stuff[4096];
40         va_list ap;
41         va_start(ap, fmt);
42         vsnprintf(stuff, sizeof(stuff), fmt, ap);
43         va_end(ap);
44         write(fd, stuff, strlen(stuff));
45 }
46
47 pthread_mutex_t clilock = AST_MUTEX_INITIALIZER;
48
49
50 struct ast_cli_entry *helpers = NULL;
51
52 static char load_help[] = 
53 "Usage: load <module name>\n"
54 "       Loads the specified module into Asterisk.\n";
55
56 static char unload_help[] = 
57 "Usage: unload [-f|-h] <module name>\n"
58 "       Unloads the specified module from Asterisk.  The -f\n"
59 "       option causes the module to be unloaded even if it is\n"
60 "       in use (may cause a crash) and the -h module causes the\n"
61 "       module to be unloaded even if the module says it cannot, \n"
62 "       which almost always will cause a crash.\n";
63
64 static char help_help[] =
65 "Usage: help [topic]\n"
66 "       When called with a topic as an argument, displays usage\n"
67 "       information on the given command.  If called without a\n"
68 "       topic, it provides a list of commands.\n";
69
70 static char chanlist_help[] = 
71 "Usage: show channels\n"
72 "       Lists currently defined channels and some information about\n"
73 "       them.\n";
74
75 static char reload_help[] = 
76 "Usage: reload\n"
77 "       Reloads configuration files for all modules which support\n"
78 "       reloading.\n";
79
80 static char set_verbose_help[] = 
81 "Usage: set verbose <level>\n"
82 "       Sets level of verbose messages to be displayed.  0 means\n"
83 "       no messages should be displayed.\n";
84
85 static char softhangup_help[] =
86 "Usage: soft hangup <channel>\n"
87 "       Request that a channel be hung up.  The hangup takes effect\n"
88 "       the next time the driver reads or writes from the channel\n";
89
90 static int handle_load(int fd, int argc, char *argv[])
91 {
92         if (argc != 2)
93                 return RESULT_SHOWUSAGE;
94         if (ast_load_resource(argv[1])) {
95                 ast_cli(fd, "Unable to load module %s\n", argv[1]);
96                 return RESULT_FAILURE;
97         }
98         return RESULT_SUCCESS;
99 }
100
101 static int handle_reload(int fd, int argc, char *argv[])
102 {
103         if (argc != 1)
104                 return RESULT_SHOWUSAGE;
105         ast_module_reload();
106         return RESULT_SUCCESS;
107 }
108
109 static int handle_set_verbose(int fd, int argc, char *argv[])
110 {
111         int val;
112         /* Has a hidden 'at least' argument */
113         if ((argc != 3) && (argc != 4))
114                 return RESULT_SHOWUSAGE;
115         if ((argc == 4) && strcasecmp(argv[2], "atleast"))
116                 return RESULT_SHOWUSAGE;
117         if (argc == 3)
118                 option_verbose = atoi(argv[2]);
119         else {
120                 val = atoi(argv[3]);
121                 if (val > option_verbose)
122                         option_verbose = val;
123         }
124         return RESULT_SUCCESS;
125 }
126
127 static int handle_unload(int fd, int argc, char *argv[])
128 {
129         int x;
130         int force=AST_FORCE_SOFT;
131         if (argc < 2)
132                 return RESULT_SHOWUSAGE;
133         for (x=1;x<argc;x++) {
134                 if (argv[x][0] == '-') {
135                         switch(argv[x][1]) {
136                         case 'f':
137                                 force = AST_FORCE_FIRM;
138                                 break;
139                         case 'h':
140                                 force = AST_FORCE_HARD;
141                                 break;
142                         default:
143                                 return RESULT_SHOWUSAGE;
144                         }
145                 } else if (x !=  argc - 1) 
146                         return RESULT_SHOWUSAGE;
147                 else if (ast_unload_resource(argv[x], force)) {
148                         ast_cli(fd, "Unable to unload resource %s\n", argv[x]);
149                         return RESULT_FAILURE;
150                 }
151         }
152         return RESULT_SUCCESS;
153 }
154
155 #define MODLIST_FORMAT  "%-20s %-40.40s %-10d\n"
156 #define MODLIST_FORMAT2 "%-20s %-40.40s %-10s\n"
157
158 static pthread_mutex_t climodentrylock = AST_MUTEX_INITIALIZER;
159 static int climodentryfd = -1;
160
161 static int modlist_modentry(char *module, char *description, int usecnt)
162 {
163         ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt);
164         return 0;
165 }
166
167 static char modlist_help[] =
168 "Usage: show modules\n"
169 "       Shows Asterisk modules currently in use, and usage "
170 "statistics.\n";
171
172 static char version_help[] =
173 "Usage: show version\n"
174 "       Shows Asterisk version information.\n ";
175
176 static int handle_modlist(int fd, int argc, char *argv[])
177 {
178         if (argc != 2)
179                 return RESULT_SHOWUSAGE;
180         ast_pthread_mutex_lock(&climodentrylock);
181         climodentryfd = fd;
182         ast_cli(fd, MODLIST_FORMAT2, "Module", "Description", "Use Count");
183         ast_update_module_list(modlist_modentry);
184         climodentryfd = -1;
185         ast_pthread_mutex_unlock(&climodentrylock);
186         return RESULT_SUCCESS;
187 }
188
189 static int handle_version(int fd, int argc, char *argv[])
190 {
191         if (argc != 2)
192                 return RESULT_SHOWUSAGE;
193         ast_cli(fd, "%s\n", VERSION_INFO);
194         return RESULT_SUCCESS;
195 }
196 static int handle_chanlist(int fd, int argc, char *argv[])
197 {
198 #define FORMAT_STRING  "%15s  (%-10s %-12s %-4d) %7s %-12s  %-15s\n"
199 #define FORMAT_STRING2 "%15s  (%-10s %-12s %-4s) %7s %-12s  %-15s\n"
200         struct ast_channel *c=NULL;
201         int numchans = 0;
202         if (argc != 2)
203                 return RESULT_SHOWUSAGE;
204         c = ast_channel_walk(NULL);
205         ast_cli(fd, FORMAT_STRING2, "Channel", "Context", "Extension", "Pri", "State", "Appl.", "Data");
206         while(c) {
207                 ast_cli(fd, FORMAT_STRING, c->name, c->context, c->exten, c->priority, ast_state2str(c->_state),
208                 c->appl ? c->appl : "(None)", c->data ? ( strlen(c->data) ? c->data : "(Empty)" ): "(None)");
209                 numchans++;
210                 c = ast_channel_walk(c);
211         }
212         ast_cli(fd, "%d active channel(s)\n", numchans);
213         return RESULT_SUCCESS;
214 }
215
216 static char showchan_help[] = 
217 "Usage: show channel <channel>\n"
218 "       Shows lots of information about the specified channel.\n";
219
220 static char debugchan_help[] = 
221 "Usage: debug channel <channel>\n"
222 "       Enables debugging on a specific channel.\n";
223
224 static char nodebugchan_help[] = 
225 "Usage: no debug channel <channel>\n"
226 "       Disables debugging on a specific channel.\n";
227
228 static char commandcomplete_help[] = 
229 "Usage: _command complete \"<line>\" text state\n"
230 "       This function is used internally to help with command completion and should.\n"
231 "       never be called by the user directly.\n";
232
233 static char commandnummatches_help[] = 
234 "Usage: _command nummatches \"<line>\" text \n"
235 "       This function is used internally to help with command completion and should.\n"
236 "       never be called by the user directly.\n";
237
238 static char commandmatchesarray_help[] = 
239 "Usage: _command matchesarray \"<line>\" text \n"
240 "       This function is used internally to help with command completion and should.\n"
241 "       never be called by the user directly.\n";
242
243 static int handle_softhangup(int fd, int argc, char *argv[])
244 {
245         struct ast_channel *c=NULL;
246         if (argc != 3)
247                 return RESULT_SHOWUSAGE;
248         c = ast_channel_walk(NULL);
249         while(c) {
250                 if (!strcasecmp(c->name, argv[2])) {
251                         ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
252                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
253                         break;
254                 }
255                 c = ast_channel_walk(c);
256         }
257         if (!c) 
258                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
259         return RESULT_SUCCESS;
260 }
261
262 static char *__ast_cli_generator(char *text, char *word, int state, int lock);
263
264 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
265 {
266         char buf[2048];
267         int len = 0;
268         char **matches;
269         int x;
270
271         if (argc != 4)
272                 return RESULT_SHOWUSAGE;
273         buf[len] = '\0';
274         matches = ast_cli_completion_matches(argv[2], argv[3]);
275         if (matches) {
276                 for (x=0; matches[x]; x++) {
277 #if 0
278                         printf("command matchesarray for '%s' %s got '%s'\n", argv[2], argv[3], matches[x]);
279 #endif
280                         len += sprintf( buf + len, "%s ", matches[x]);
281                         free(matches[x]);
282                         matches[x] = NULL;
283                 }
284                 free(matches);
285         }
286 #if 0
287         printf("array for '%s' %s got '%s'\n", argv[2], argv[3], buf);
288 #endif
289         
290         if (buf) {
291                 ast_cli(fd, buf);
292         } else
293                 ast_cli(fd, "NULL\n");
294
295         return RESULT_SUCCESS;
296 }
297
298
299
300 static int handle_commandnummatches(int fd, int argc, char *argv[])
301 {
302         int matches = 0;
303
304         if (argc != 4)
305                 return RESULT_SHOWUSAGE;
306
307         matches = ast_cli_generatornummatches(argv[2], argv[3]);
308
309 #if 0
310         printf("Search for '%s' %s got '%d'\n", argv[2], argv[3], matches);
311 #endif
312         ast_cli(fd, "%d", matches);
313
314         return RESULT_SUCCESS;
315 }
316
317 static int handle_commandcomplete(int fd, int argc, char *argv[])
318 {
319         char *buf;
320 #if 0
321         printf("Search for %d args: '%s', '%s', '%s', '%s'\n", argc, argv[0], argv[1], argv[2], argv[3]);
322 #endif  
323         if (argc != 5)
324                 return RESULT_SHOWUSAGE;
325         buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
326 #if 0
327         printf("Search for '%s' %s %d got '%s'\n", argv[2], argv[3], atoi(argv[4]), buf);
328 #endif  
329         if (buf) {
330                 ast_cli(fd, buf);
331                 free(buf);
332         } else
333                 ast_cli(fd, "NULL\n");
334         return RESULT_SUCCESS;
335 }
336
337 static int handle_debugchan(int fd, int argc, char *argv[])
338 {
339         struct ast_channel *c=NULL;
340         if (argc != 3)
341                 return RESULT_SHOWUSAGE;
342         c = ast_channel_walk(NULL);
343         while(c) {
344                 if (!strcasecmp(c->name, argv[2])) {
345                         c->fin |= 0x80000000;
346                         c->fout |= 0x80000000;
347                         break;
348                 }
349                 c = ast_channel_walk(c);
350         }
351         if (c)
352                 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
353         else
354                 ast_cli(fd, "No such channel %s\n", argv[2]);
355         return RESULT_SUCCESS;
356 }
357
358 static int handle_nodebugchan(int fd, int argc, char *argv[])
359 {
360         struct ast_channel *c=NULL;
361         if (argc != 4)
362                 return RESULT_SHOWUSAGE;
363         c = ast_channel_walk(NULL);
364         while(c) {
365                 if (!strcasecmp(c->name, argv[3])) {
366                         c->fin &= 0x7fffffff;
367                         c->fout &= 0x7fffffff;
368                         break;
369                 }
370                 c = ast_channel_walk(c);
371         }
372         if (c)
373                 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
374         else
375                 ast_cli(fd, "No such channel %s\n", argv[2]);
376         return RESULT_SUCCESS;
377 }
378                 
379         
380
381 static int handle_showchan(int fd, int argc, char *argv[])
382 {
383         struct ast_channel *c=NULL;
384         if (argc != 3)
385                 return RESULT_SHOWUSAGE;
386         c = ast_channel_walk(NULL);
387         while(c) {
388                 if (!strcasecmp(c->name, argv[2])) {
389                         ast_cli(fd, 
390         " -- General --\n"
391         "           Name: %s\n"
392         "           Type: %s\n"
393         "      Caller ID: %s\n"
394         "    DNID Digits: %s\n"
395         "          State: %s (%d)\n"
396         "          Rings: %d\n"
397         "   NativeFormat: %d\n"
398         "    WriteFormat: %d\n"
399         "     ReadFormat: %d\n"
400         "1st File Descriptor: %d\n"
401         "      Frames in: %d%s\n"
402         "     Frames out: %d%s\n"
403         " Time to Hangup: %d\n"
404         " --   PBX   --\n"
405         "        Context: %s\n"
406         "      Extension: %s\n"
407         "       Priority: %d\n"
408         "     Call Group: %d\n"
409         "   Pickup Group: %d\n"
410         "    Application: %s\n"
411         "           Data: %s\n"
412         "          Stack: %d\n"
413         "    Blocking in: %s\n",
414         c->name, c->type, 
415         (c->callerid ? c->callerid : "(N/A)"),
416         (c->dnid ? c->dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings, c->nativeformats, c->writeformat, c->readformat,
417         c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
418         c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", c->whentohangup,
419         c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
420         ( c-> data ? (strlen(c->data) ? c->data : "(Empty)") : "(None)"),
421         c->stack, (c->blocking ? c->blockproc : "(Not Blocking)"));
422         
423                 break;
424                 }
425                 c = ast_channel_walk(c);
426         }
427         if (!c) 
428                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
429         return RESULT_SUCCESS;
430 }
431
432 static char *complete_ch(char *line, char *word, int pos, int state)
433 {
434         struct ast_channel *c;
435         int which=0;
436         c = ast_channel_walk(NULL);
437         while(c) {
438                 if (!strncasecmp(word, c->name, strlen(word))) {
439                         if (++which > state)
440                                 break;
441                 }
442                 c = ast_channel_walk(c);
443         }
444         return c ? strdup(c->name) : NULL;
445 }
446
447 static char *complete_fn(char *line, char *word, int pos, int state)
448 {
449         char *c;
450         char filename[256];
451         if (pos != 1)
452                 return NULL;
453         if (word[0] == '/')
454                 strncpy(filename, word, sizeof(filename)-1);
455         else
456                 snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_MODULE_DIR, word);
457         c = (char*)filename_completion_function(filename, state);
458         if (c && word[0] != '/')
459                 c += (strlen((char*)ast_config_AST_MODULE_DIR) + 1);
460         return c ? strdup(c) : c;
461 }
462
463 static int handle_help(int fd, int argc, char *argv[]);
464
465 static struct ast_cli_entry builtins[] = {
466         /* Keep alphabetized */
467         { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
468         { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
469         { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
470         { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch },
471         { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help },
472         { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
473         { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch },
474         { { "reload", NULL }, handle_reload, "Reload configuration", reload_help },
475         { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
476         { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch },
477         { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help },
478         { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
479         { { "show", "version", NULL }, handle_version, "Display version info", version_help },
480         { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch },
481         { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
482         { { NULL }, NULL, NULL, NULL }
483 };
484
485 static struct ast_cli_entry *find_cli(char *cmds[], int exact)
486 {
487         int x;
488         int y;
489         int match;
490         struct ast_cli_entry *e=NULL;
491         for (x=0;builtins[x].cmda[0];x++) {
492                 /* start optimistic */
493                 match = 1;
494                 for (y=0;match && cmds[y]; y++) {
495                         /* If there are no more words in the candidate command, then we're
496                            there.  */
497                         if (!builtins[x].cmda[y] && !exact)
498                                 break;
499                         /* If there are no more words in the command (and we're looking for
500                            an exact match) or there is a difference between the two words,
501                            then this is not a match */
502                         if (!builtins[x].cmda[y] || strcasecmp(builtins[x].cmda[y], cmds[y]))
503                                 match = 0;
504                 }
505                 /* If more words are needed to complete the command then this is not
506                    a candidate (unless we're looking for a really inexact answer  */
507                 if ((exact > -1) && builtins[x].cmda[y])
508                         match = 0;
509                 if (match)
510                         return &builtins[x];
511         }
512         for (e=helpers;e;e=e->next) {
513                 match = 1;
514                 for (y=0;match && cmds[y]; y++) {
515                         if (!e->cmda[y] && !exact)
516                                 break;
517                         if (!e->cmda[y] || strcasecmp(e->cmda[y], cmds[y]))
518                                 match = 0;
519                 }
520                 if ((exact > -1) && e->cmda[y])
521                         match = 0;
522                 if (match)
523                         break;
524         }
525         return e;
526 }
527
528 static void join(char *s, int len, char *w[])
529 {
530         int x;
531         /* Join words into a string */
532         strcpy(s, "");
533         for (x=0;w[x];x++) {
534                 if (x)
535                         strncat(s, " ", len - strlen(s));
536                 strncat(s, w[x], len - strlen(s));
537         }
538 }
539
540 static void join2(char *s, int len, char *w[])
541 {
542         int x;
543         /* Join words into a string */
544         strcpy(s, "");
545         for (x=0;w[x];x++) {
546                 strncat(s, w[x], len - strlen(s));
547         }
548 }
549
550 static char *find_best(char *argv[])
551 {
552         static char cmdline[80];
553         int x;
554         /* See how close we get, then print the  */
555         char *myargv[AST_MAX_CMD_LEN];
556         for (x=0;x<AST_MAX_CMD_LEN;x++)
557                 myargv[x]=NULL;
558         for (x=0;argv[x];x++) {
559                 myargv[x] = argv[x];
560                 if (!find_cli(myargv, -1))
561                         break;
562         }
563         join(cmdline, sizeof(cmdline), myargv);
564         return cmdline;
565 }
566
567 int ast_cli_unregister(struct ast_cli_entry *e)
568 {
569         struct ast_cli_entry *cur, *l=NULL;
570         ast_pthread_mutex_lock(&clilock);
571         cur = helpers;
572         while(cur) {
573                 if (e == cur) {
574                         if (e->inuse) {
575                                 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
576                         } else {
577                                 /* Rewrite */
578                                 if (l)
579                                         l->next = e->next;
580                                 else
581                                         helpers = e->next;
582                                 e->next = NULL;
583                                 break;
584                         }
585                 }
586                 l = cur;
587                 cur = cur->next;
588         }
589         ast_pthread_mutex_unlock(&clilock);
590         return 0;
591 }
592
593 int ast_cli_register(struct ast_cli_entry *e)
594 {
595         struct ast_cli_entry *cur, *l=NULL;
596         char fulle[80] ="", fulltst[80] ="";
597         static int len;
598         ast_pthread_mutex_lock(&clilock);
599         join2(fulle, sizeof(fulle), e->cmda);
600         if (find_cli(e->cmda, -1)) {
601                 ast_pthread_mutex_unlock(&clilock);
602                 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
603                 return -1;
604         }
605         cur = helpers;
606         while(cur) {
607                 join2(fulltst, sizeof(fulltst), cur->cmda);
608                 len = strlen(fulltst);
609                 if (strlen(fulle) < len)
610                         len = strlen(fulle);
611                 if (strncasecmp(fulle, fulltst, len) < 0) {
612                         if (l) {
613                                 e->next = l->next;
614                                 l->next = e;
615                         } else {
616                                 e->next = helpers;
617                                 helpers = e;
618                         }
619                         break;
620                 }
621                 l = cur;
622                 cur = cur->next;
623         }
624         if (!cur) {
625                 if (l)
626                         l->next = e;
627                 else
628                         helpers = e;
629                 e->next = NULL;
630         }
631         ast_pthread_mutex_unlock(&clilock);
632         return 0;
633 }
634
635 static int help_workhorse(int fd, char *match[])
636 {
637         char fullcmd1[80];
638         char fullcmd2[80];
639         char matchstr[80];
640         char *fullcmd;
641         struct ast_cli_entry *e, *e1, *e2;
642         e1 = builtins;
643         e2 = helpers;
644         if (match)
645                 join(matchstr, sizeof(matchstr), match);
646         while(e1->cmda[0] || e2) {
647                 if (e2)
648                         join(fullcmd2, sizeof(fullcmd2), e2->cmda);
649                 if (e1->cmda[0])
650                         join(fullcmd1, sizeof(fullcmd1), e1->cmda);
651                 if (!e1->cmda[0] || 
652                                 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
653                         /* Use e2 */
654                         e = e2;
655                         fullcmd = fullcmd2;
656                         /* Increment by going to next */
657                         e2 = e2->next;
658                 } else {
659                         /* Use e1 */
660                         e = e1;
661                         fullcmd = fullcmd1;
662                         e1++;
663                 }
664                 /* Hide commands that start with '_' */
665                 if (fullcmd[0] == '_')
666                         continue;
667                 if (match) {
668                         if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
669                                 continue;
670                         }
671                 }
672                 ast_cli(fd, "%20.20s   %s\n", fullcmd, e->summary);
673         }
674         return 0;
675 }
676
677 static int handle_help(int fd, int argc, char *argv[]) {
678         struct ast_cli_entry *e;
679         char fullcmd[80];
680         if ((argc < 1))
681                 return RESULT_SHOWUSAGE;
682         if (argc > 1) {
683                 e = find_cli(argv + 1, 1);
684                 if (e) 
685                         ast_cli(fd, e->usage);
686                 else {
687                         if (find_cli(argv + 1, -1)) {
688                                 return help_workhorse(fd, argv + 1);
689                         } else {
690                                 join(fullcmd, sizeof(fullcmd), argv+1);
691                                 ast_cli(fd, "No such command '%s'.\n", fullcmd);
692                         }
693                 }
694         } else {
695                 return help_workhorse(fd, NULL);
696         }
697         return RESULT_SUCCESS;
698 }
699
700 static char *parse_args(char *s, int *max, char *argv[])
701 {
702         char *dup, *cur;
703         int x=0;
704         int quoted=0;
705         int escaped=0;
706         int whitespace=1;
707
708         dup = strdup(s);
709         if (dup) {
710                 cur = dup;
711                 while(*s) {
712                         switch(*s) {
713                         case '"':
714                                 /* If it's escaped, put a literal quote */
715                                 if (escaped) 
716                                         goto normal;
717                                 else 
718                                         quoted = !quoted;
719                                 if (quoted && whitespace) {
720                                         /* If we're starting a quote, coming off white space start a new word, too */
721                                         argv[x++] = cur;
722                                         whitespace=0;
723                                 }
724                                 escaped = 0;
725                                 break;
726                         case ' ':
727                         case '\t':
728                                 if (!quoted && !escaped) {
729                                         /* If we're not quoted, mark this as whitespace, and
730                                            end the previous argument */
731                                         whitespace = 1;
732                                         *(cur++) = '\0';
733                                 } else
734                                         /* Otherwise, just treat it as anything else */ 
735                                         goto normal;
736                                 break;
737                         case '\\':
738                                 /* If we're escaped, print a literal, otherwise enable escaping */
739                                 if (escaped) {
740                                         goto normal;
741                                 } else {
742                                         escaped=1;
743                                 }
744                                 break;
745                         default:
746 normal:
747                                 if (whitespace) {
748                                         if (x >= AST_MAX_ARGS -1) {
749                                                 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
750                                                 break;
751                                         }
752                                         /* Coming off of whitespace, start the next argument */
753                                         argv[x++] = cur;
754                                         whitespace=0;
755                                 }
756                                 *(cur++) = *s;
757                                 escaped=0;
758                         }
759                         s++;
760                 }
761                 /* Null terminate */
762                 *(cur++) = '\0';
763                 argv[x] = NULL;
764                 *max = x;
765         }
766         return dup;
767 }
768
769 /* This returns the number of unique matches for the generator */
770 int ast_cli_generatornummatches(char *text, char *word)
771 {
772         int matches = 0, i = 0;
773         char *buf, *oldbuf = NULL;
774
775
776         while ( (buf = ast_cli_generator(text, word, i)) ) {
777                 if (++i > 1 && strcmp(buf,oldbuf) == 0)  {
778                                 continue;
779                 }
780                 oldbuf = buf;
781                 matches++;
782         }
783
784         return matches;
785 }
786
787 char **ast_cli_completion_matches(char *text, char *word)
788 {
789         char **match_list = NULL, *retstr, *prevstr;
790         size_t match_list_len, max_equal, which, i;
791         int matches = 0;
792
793         match_list_len = 1;
794         while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
795                 if (matches + 1 >= match_list_len) {
796                         match_list_len <<= 1;
797                         match_list = realloc(match_list, match_list_len * sizeof(char *));
798                 }
799                 match_list[++matches] = retstr;
800         }
801
802         if (!match_list)
803                 return (char **) NULL;
804
805         which = 2;
806         prevstr = match_list[1];
807         max_equal = strlen(prevstr);
808         for (; which <= matches; which++) {
809                 for (i = 0; i < max_equal && prevstr[i] == match_list[which][i]; i++)
810                         continue;
811                 max_equal = i;
812         }
813
814         retstr = malloc(max_equal + 1);
815         (void) strncpy(retstr, match_list[1], max_equal);
816         retstr[max_equal] = '\0';
817         match_list[0] = retstr;
818
819         if (matches + 1 >= match_list_len)
820                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
821         match_list[matches + 1] = (char *) NULL;
822
823         return (match_list);
824 }
825
826 static char *__ast_cli_generator(char *text, char *word, int state, int lock)
827 {
828         char *argv[AST_MAX_ARGS];
829         struct ast_cli_entry *e, *e1, *e2;
830         int x;
831         int matchnum=0;
832         char *dup, *res;
833         char fullcmd1[80];
834         char fullcmd2[80];
835         char matchstr[80];
836         char *fullcmd;
837
838         if ((dup = parse_args(text, &x, argv))) {
839                 join(matchstr, sizeof(matchstr), argv);
840                 if (lock)
841                         ast_pthread_mutex_lock(&clilock);
842                 e1 = builtins;
843                 e2 = helpers;
844                 while(e1->cmda[0] || e2) {
845                         if (e2)
846                                 join(fullcmd2, sizeof(fullcmd2), e2->cmda);
847                         if (e1->cmda[0])
848                                 join(fullcmd1, sizeof(fullcmd1), e1->cmda);
849                         if (!e1->cmda[0] || 
850                                         (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
851                                 /* Use e2 */
852                                 e = e2;
853                                 fullcmd = fullcmd2;
854                                 /* Increment by going to next */
855                                 e2 = e2->next;
856                         } else {
857                                 /* Use e1 */
858                                 e = e1;
859                                 fullcmd = fullcmd1;
860                                 e1++;
861                         }
862                         if ((fullcmd[0] != '_') && !strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
863                                 /* We contain the first part of one or more commands */
864                                 matchnum++;
865                                 if (matchnum > state) {
866                                         /* Now, what we're supposed to return is the next word... */
867                                         if (strlen(word) && x>0) {
868                                                 res = e->cmda[x-1];
869                                         } else {
870                                                 res = e->cmda[x];
871                                         }
872                                         if (res) {
873                                                 if (lock)
874                                                         ast_pthread_mutex_unlock(&clilock);
875                                                 free(dup);
876                                                 return res ? res : NULL;
877                                         }
878                                 }
879                         }
880                         if (e->generator && !strncasecmp(matchstr, fullcmd, strlen(fullcmd))) {
881                                 /* We have a command in its entirity within us -- theoretically only one
882                                    command can have this occur */
883                                 fullcmd = e->generator(text, word, (strlen(word) ? (x - 1) : (x)), state);
884                                 if (lock)
885                                         ast_pthread_mutex_unlock(&clilock);
886                                 return fullcmd;
887                         }
888                         
889                 }
890                 if (lock)
891                         ast_pthread_mutex_unlock(&clilock);
892                 free(dup);
893         }
894         return NULL;
895 }
896
897 char *ast_cli_generator(char *text, char *word, int state)
898 {
899         return __ast_cli_generator(text, word, state, 1);
900 }
901
902 int ast_cli_command(int fd, char *s)
903 {
904         char *argv[AST_MAX_ARGS];
905         struct ast_cli_entry *e;
906         int x;
907         char *dup;
908         x = AST_MAX_ARGS;
909         if ((dup = parse_args(s, &x, argv))) {
910                 /* We need at least one entry, or ignore */
911                 if (x > 0) {
912                         ast_pthread_mutex_lock(&clilock);
913                         e = find_cli(argv, 0);
914                         if (e)
915                                 e->inuse++;
916                         ast_pthread_mutex_unlock(&clilock);
917                         if (e) {
918                                 switch(e->handler(fd, x, argv)) {
919                                 case RESULT_SHOWUSAGE:
920                                         ast_cli(fd, e->usage);
921                                         break;
922                                 default:
923                                 }
924                         } else 
925                                 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
926                         if (e) {
927                                 ast_pthread_mutex_lock(&clilock);
928                                 e->inuse--;
929                                 ast_pthread_mutex_unlock(&clilock);
930                         }
931                 }
932                 free(dup);
933         } else {
934                 ast_log(LOG_WARNING, "Out of memory\n");        
935                 return -1;
936         }
937         return 0;
938 }