Fix some leaks in CLI (thanks James)
[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         "    Application: %s\n"
409         "           Data: %s\n"
410         "          Stack: %d\n"
411         "    Blocking in: %s\n",
412         c->name, c->type, 
413         (c->callerid ? c->callerid : "(N/A)"),
414         (c->dnid ? c->dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings, c->nativeformats, c->writeformat, c->readformat,
415         c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
416         c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", c->whentohangup,
417         c->context, c->exten, c->priority, ( c->appl ? c->appl : "(N/A)" ),
418         ( c-> data ? (strlen(c->data) ? c->data : "(Empty)") : "(None)"),
419         c->stack, (c->blocking ? c->blockproc : "(Not Blocking)"));
420         
421                 break;
422                 }
423                 c = ast_channel_walk(c);
424         }
425         if (!c) 
426                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
427         return RESULT_SUCCESS;
428 }
429
430 static char *complete_ch(char *line, char *word, int pos, int state)
431 {
432         struct ast_channel *c;
433         int which=0;
434         c = ast_channel_walk(NULL);
435         while(c) {
436                 if (!strncasecmp(word, c->name, strlen(word))) {
437                         if (++which > state)
438                                 break;
439                 }
440                 c = ast_channel_walk(c);
441         }
442         return c ? strdup(c->name) : NULL;
443 }
444
445 static char *complete_fn(char *line, char *word, int pos, int state)
446 {
447         char *c;
448         char filename[256];
449         if (pos != 1)
450                 return NULL;
451         if (word[0] == '/')
452                 strncpy(filename, word, sizeof(filename)-1);
453         else
454                 snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_MODULE_DIR, word);
455         c = (char*)filename_completion_function(filename, state);
456         if (c && word[0] != '/')
457                 c += (strlen((char*)ast_config_AST_MODULE_DIR) + 1);
458         return c ? strdup(c) : c;
459 }
460
461 static int handle_help(int fd, int argc, char *argv[]);
462
463 static struct ast_cli_entry builtins[] = {
464         /* Keep alphabetized */
465         { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
466         { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
467         { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
468         { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch },
469         { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help },
470         { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
471         { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch },
472         { { "reload", NULL }, handle_reload, "Reload configuration", reload_help },
473         { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
474         { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch },
475         { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help },
476         { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
477         { { "show", "version", NULL }, handle_version, "Display version info", version_help },
478         { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch },
479         { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
480         { { NULL }, NULL, NULL, NULL }
481 };
482
483 static struct ast_cli_entry *find_cli(char *cmds[], int exact)
484 {
485         int x;
486         int y;
487         int match;
488         struct ast_cli_entry *e=NULL;
489         for (x=0;builtins[x].cmda[0];x++) {
490                 /* start optimistic */
491                 match = 1;
492                 for (y=0;match && cmds[y]; y++) {
493                         /* If there are no more words in the candidate command, then we're
494                            there.  */
495                         if (!builtins[x].cmda[y] && !exact)
496                                 break;
497                         /* If there are no more words in the command (and we're looking for
498                            an exact match) or there is a difference between the two words,
499                            then this is not a match */
500                         if (!builtins[x].cmda[y] || strcasecmp(builtins[x].cmda[y], cmds[y]))
501                                 match = 0;
502                 }
503                 /* If more words are needed to complete the command then this is not
504                    a candidate (unless we're looking for a really inexact answer  */
505                 if ((exact > -1) && builtins[x].cmda[y])
506                         match = 0;
507                 if (match)
508                         return &builtins[x];
509         }
510         for (e=helpers;e;e=e->next) {
511                 match = 1;
512                 for (y=0;match && cmds[y]; y++) {
513                         if (!e->cmda[y] && !exact)
514                                 break;
515                         if (!e->cmda[y] || strcasecmp(e->cmda[y], cmds[y]))
516                                 match = 0;
517                 }
518                 if ((exact > -1) && e->cmda[y])
519                         match = 0;
520                 if (match)
521                         break;
522         }
523         return e;
524 }
525
526 static void join(char *s, int len, char *w[])
527 {
528         int x;
529         /* Join words into a string */
530         strcpy(s, "");
531         for (x=0;w[x];x++) {
532                 if (x)
533                         strncat(s, " ", len - strlen(s));
534                 strncat(s, w[x], len - strlen(s));
535         }
536 }
537
538 static void join2(char *s, int len, char *w[])
539 {
540         int x;
541         /* Join words into a string */
542         strcpy(s, "");
543         for (x=0;w[x];x++) {
544                 strncat(s, w[x], len - strlen(s));
545         }
546 }
547
548 static char *find_best(char *argv[])
549 {
550         static char cmdline[80];
551         int x;
552         /* See how close we get, then print the  */
553         char *myargv[AST_MAX_CMD_LEN];
554         for (x=0;x<AST_MAX_CMD_LEN;x++)
555                 myargv[x]=NULL;
556         for (x=0;argv[x];x++) {
557                 myargv[x] = argv[x];
558                 if (!find_cli(myargv, -1))
559                         break;
560         }
561         join(cmdline, sizeof(cmdline), myargv);
562         return cmdline;
563 }
564
565 int ast_cli_unregister(struct ast_cli_entry *e)
566 {
567         struct ast_cli_entry *cur, *l=NULL;
568         ast_pthread_mutex_lock(&clilock);
569         cur = helpers;
570         while(cur) {
571                 if (e == cur) {
572                         if (e->inuse) {
573                                 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
574                         } else {
575                                 /* Rewrite */
576                                 if (l)
577                                         l->next = e->next;
578                                 else
579                                         helpers = e->next;
580                                 e->next = NULL;
581                                 break;
582                         }
583                 }
584                 l = cur;
585                 cur = cur->next;
586         }
587         ast_pthread_mutex_unlock(&clilock);
588         return 0;
589 }
590
591 int ast_cli_register(struct ast_cli_entry *e)
592 {
593         struct ast_cli_entry *cur, *l=NULL;
594         char fulle[80] ="", fulltst[80] ="";
595         static int len;
596         ast_pthread_mutex_lock(&clilock);
597         join2(fulle, sizeof(fulle), e->cmda);
598         if (find_cli(e->cmda, -1)) {
599                 ast_pthread_mutex_unlock(&clilock);
600                 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
601                 return -1;
602         }
603         cur = helpers;
604         while(cur) {
605                 join2(fulltst, sizeof(fulltst), cur->cmda);
606                 len = strlen(fulltst);
607                 if (strlen(fulle) < len)
608                         len = strlen(fulle);
609                 if (strncasecmp(fulle, fulltst, len) < 0) {
610                         if (l) {
611                                 e->next = l->next;
612                                 l->next = e;
613                         } else {
614                                 e->next = helpers;
615                                 helpers = e;
616                         }
617                         break;
618                 }
619                 l = cur;
620                 cur = cur->next;
621         }
622         if (!cur) {
623                 if (l)
624                         l->next = e;
625                 else
626                         helpers = e;
627                 e->next = NULL;
628         }
629         ast_pthread_mutex_unlock(&clilock);
630         return 0;
631 }
632
633 static int help_workhorse(int fd, char *match[])
634 {
635         char fullcmd1[80];
636         char fullcmd2[80];
637         char matchstr[80];
638         char *fullcmd;
639         struct ast_cli_entry *e, *e1, *e2;
640         e1 = builtins;
641         e2 = helpers;
642         if (match)
643                 join(matchstr, sizeof(matchstr), match);
644         while(e1->cmda[0] || e2) {
645                 if (e2)
646                         join(fullcmd2, sizeof(fullcmd2), e2->cmda);
647                 if (e1->cmda[0])
648                         join(fullcmd1, sizeof(fullcmd1), e1->cmda);
649                 if (!e1->cmda[0] || 
650                                 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
651                         /* Use e2 */
652                         e = e2;
653                         fullcmd = fullcmd2;
654                         /* Increment by going to next */
655                         e2 = e2->next;
656                 } else {
657                         /* Use e1 */
658                         e = e1;
659                         fullcmd = fullcmd1;
660                         e1++;
661                 }
662                 /* Hide commands that start with '_' */
663                 if (fullcmd[0] == '_')
664                         continue;
665                 if (match) {
666                         if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
667                                 continue;
668                         }
669                 }
670                 ast_cli(fd, "%20.20s   %s\n", fullcmd, e->summary);
671         }
672         return 0;
673 }
674
675 static int handle_help(int fd, int argc, char *argv[]) {
676         struct ast_cli_entry *e;
677         char fullcmd[80];
678         if ((argc < 1))
679                 return RESULT_SHOWUSAGE;
680         if (argc > 1) {
681                 e = find_cli(argv + 1, 1);
682                 if (e) 
683                         ast_cli(fd, e->usage);
684                 else {
685                         if (find_cli(argv + 1, -1)) {
686                                 return help_workhorse(fd, argv + 1);
687                         } else {
688                                 join(fullcmd, sizeof(fullcmd), argv+1);
689                                 ast_cli(fd, "No such command '%s'.\n", fullcmd);
690                         }
691                 }
692         } else {
693                 return help_workhorse(fd, NULL);
694         }
695         return RESULT_SUCCESS;
696 }
697
698 static char *parse_args(char *s, int *max, char *argv[])
699 {
700         char *dup, *cur;
701         int x=0;
702         int quoted=0;
703         int escaped=0;
704         int whitespace=1;
705
706         dup = strdup(s);
707         if (dup) {
708                 cur = dup;
709                 while(*s) {
710                         switch(*s) {
711                         case '"':
712                                 /* If it's escaped, put a literal quote */
713                                 if (escaped) 
714                                         goto normal;
715                                 else 
716                                         quoted = !quoted;
717                                 if (quoted && whitespace) {
718                                         /* If we're starting a quote, coming off white space start a new word, too */
719                                         argv[x++] = cur;
720                                         whitespace=0;
721                                 }
722                                 escaped = 0;
723                                 break;
724                         case ' ':
725                         case '\t':
726                                 if (!quoted && !escaped) {
727                                         /* If we're not quoted, mark this as whitespace, and
728                                            end the previous argument */
729                                         whitespace = 1;
730                                         *(cur++) = '\0';
731                                 } else
732                                         /* Otherwise, just treat it as anything else */ 
733                                         goto normal;
734                                 break;
735                         case '\\':
736                                 /* If we're escaped, print a literal, otherwise enable escaping */
737                                 if (escaped) {
738                                         goto normal;
739                                 } else {
740                                         escaped=1;
741                                 }
742                                 break;
743                         default:
744 normal:
745                                 if (whitespace) {
746                                         if (x >= AST_MAX_ARGS -1) {
747                                                 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
748                                                 break;
749                                         }
750                                         /* Coming off of whitespace, start the next argument */
751                                         argv[x++] = cur;
752                                         whitespace=0;
753                                 }
754                                 *(cur++) = *s;
755                                 escaped=0;
756                         }
757                         s++;
758                 }
759                 /* Null terminate */
760                 *(cur++) = '\0';
761                 argv[x] = NULL;
762                 *max = x;
763         }
764         return dup;
765 }
766
767 /* This returns the number of unique matches for the generator */
768 int ast_cli_generatornummatches(char *text, char *word)
769 {
770         int matches = 0, i = 0;
771         char *buf, *oldbuf = NULL;
772
773
774         while ( (buf = ast_cli_generator(text, word, i)) ) {
775                 if (++i > 1 && strcmp(buf,oldbuf) == 0)  {
776                                 free(buf);
777                                 continue;
778                 }
779                 if (oldbuf)
780                         free(oldbuf);
781                 oldbuf = buf;
782                 matches++;
783         }
784
785         return matches;
786 }
787
788 char **ast_cli_completion_matches(char *text, char *word)
789 {
790         char **match_list = NULL, *retstr, *prevstr;
791         size_t match_list_len, max_equal, which, i;
792         int matches = 0;
793
794         match_list_len = 1;
795         while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
796                 if (matches + 1 >= match_list_len) {
797                         match_list_len <<= 1;
798                         match_list = realloc(match_list, match_list_len * sizeof(char *));
799                 }
800                 match_list[++matches] = retstr;
801         }
802
803         if (!match_list)
804                 return (char **) NULL;
805
806         which = 2;
807         prevstr = match_list[1];
808         max_equal = strlen(prevstr);
809         for (; which <= matches; which++) {
810                 for (i = 0; i < max_equal && prevstr[i] == match_list[which][i]; i++)
811                         continue;
812                 max_equal = i;
813         }
814
815         retstr = malloc(max_equal + 1);
816         (void) strncpy(retstr, match_list[1], max_equal);
817         retstr[max_equal] = '\0';
818         match_list[0] = retstr;
819
820         if (matches + 1 >= match_list_len)
821                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
822         match_list[matches + 1] = (char *) NULL;
823
824         return (match_list);
825 }
826
827 static char *__ast_cli_generator(char *text, char *word, int state, int lock)
828 {
829         char *argv[AST_MAX_ARGS];
830         struct ast_cli_entry *e, *e1, *e2;
831         int x;
832         int matchnum=0;
833         char *dup, *res;
834         char fullcmd1[80];
835         char fullcmd2[80];
836         char matchstr[80];
837         char *fullcmd;
838
839         if ((dup = parse_args(text, &x, argv))) {
840                 join(matchstr, sizeof(matchstr), argv);
841                 if (lock)
842                         ast_pthread_mutex_lock(&clilock);
843                 e1 = builtins;
844                 e2 = helpers;
845                 while(e1->cmda[0] || e2) {
846                         if (e2)
847                                 join(fullcmd2, sizeof(fullcmd2), e2->cmda);
848                         if (e1->cmda[0])
849                                 join(fullcmd1, sizeof(fullcmd1), e1->cmda);
850                         if (!e1->cmda[0] || 
851                                         (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
852                                 /* Use e2 */
853                                 e = e2;
854                                 fullcmd = fullcmd2;
855                                 /* Increment by going to next */
856                                 e2 = e2->next;
857                         } else {
858                                 /* Use e1 */
859                                 e = e1;
860                                 fullcmd = fullcmd1;
861                                 e1++;
862                         }
863                         if ((fullcmd[0] != '_') && !strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
864                                 /* We contain the first part of one or more commands */
865                                 matchnum++;
866                                 if (matchnum > state) {
867                                         /* Now, what we're supposed to return is the next word... */
868                                         if (strlen(word) && x>0) {
869                                                 res = e->cmda[x-1];
870                                         } else {
871                                                 res = e->cmda[x];
872                                         }
873                                         if (res) {
874                                                 if (lock)
875                                                         ast_pthread_mutex_unlock(&clilock);
876                                                 free(dup);
877                                                 return res ? strdup(res) : NULL;
878                                         }
879                                 }
880                         }
881                         if (e->generator && !strncasecmp(matchstr, fullcmd, strlen(fullcmd))) {
882                                 /* We have a command in its entirity within us -- theoretically only one
883                                    command can have this occur */
884                                 fullcmd = e->generator(text, word, (strlen(word) ? (x - 1) : (x)), state);
885                                 if (lock)
886                                         ast_pthread_mutex_unlock(&clilock);
887                                 return fullcmd;
888                         }
889                         
890                 }
891                 if (lock)
892                         ast_pthread_mutex_unlock(&clilock);
893                 free(dup);
894         }
895         return NULL;
896 }
897
898 char *ast_cli_generator(char *text, char *word, int state)
899 {
900         return __ast_cli_generator(text, word, state, 1);
901 }
902
903 int ast_cli_command(int fd, char *s)
904 {
905         char *argv[AST_MAX_ARGS];
906         struct ast_cli_entry *e;
907         int x;
908         char *dup;
909         x = AST_MAX_ARGS;
910         if ((dup = parse_args(s, &x, argv))) {
911                 /* We need at least one entry, or ignore */
912                 if (x > 0) {
913                         ast_pthread_mutex_lock(&clilock);
914                         e = find_cli(argv, 0);
915                         if (e)
916                                 e->inuse++;
917                         ast_pthread_mutex_unlock(&clilock);
918                         if (e) {
919                                 switch(e->handler(fd, x, argv)) {
920                                 case RESULT_SHOWUSAGE:
921                                         ast_cli(fd, e->usage);
922                                         break;
923                                 default:
924                                 }
925                         } else 
926                                 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
927                         if (e) {
928                                 ast_pthread_mutex_lock(&clilock);
929                                 e->inuse--;
930                                 ast_pthread_mutex_unlock(&clilock);
931                         }
932                 }
933                 free(dup);
934         } else {
935                 ast_log(LOG_WARNING, "Out of memory\n");        
936                 return -1;
937         }
938         return 0;
939 }