mer feb 12 14:56:57 CET 2003
[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 commandcomplete_help[] = 
221 "Usage: _command complete \"<line>\" text state\n"
222 "       This function is used internally to help with command completion and should.\n"
223 "       never be called by the user directly.\n";
224
225 static char commandnummatches_help[] = 
226 "Usage: _command nummatches \"<line>\" text \n"
227 "       This function is used internally to help with command completion and should.\n"
228 "       never be called by the user directly.\n";
229
230 static char commandmatchesarray_help[] = 
231 "Usage: _command matchesarray \"<line>\" text \n"
232 "       This function is used internally to help with command completion and should.\n"
233 "       never be called by the user directly.\n";
234
235 static int handle_softhangup(int fd, int argc, char *argv[])
236 {
237         struct ast_channel *c=NULL;
238         if (argc != 3)
239                 return RESULT_SHOWUSAGE;
240         c = ast_channel_walk(NULL);
241         while(c) {
242                 if (!strcasecmp(c->name, argv[2])) {
243                         ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
244                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
245                         break;
246                 }
247                 c = ast_channel_walk(c);
248         }
249         if (!c) 
250                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
251         return RESULT_SUCCESS;
252 }
253
254 static char *__ast_cli_generator(char *text, char *word, int state, int lock);
255
256 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
257 {
258         char buf[2048];
259         int len = 0;
260         char **matches;
261         int x;
262
263         if (argc != 4)
264                 return RESULT_SHOWUSAGE;
265         buf[len] = '\0';
266         matches = ast_cli_completion_matches(argv[2], argv[3]);
267         if (matches) {
268                 for (x=0; matches[x]; x++) {
269 #if 0
270                         printf("command matchesarray for '%s' %s got '%s'\n", argv[2], argv[3], matches[x]);
271 #endif
272                         len += sprintf( buf + len, "%s ", matches[x]);
273                 }
274         }
275 #if 0
276         printf("array for '%s' %s got '%s'\n", argv[2], argv[3], buf);
277 #endif
278         
279         if (buf) {
280                 ast_cli(fd, buf);
281         } else
282                 ast_cli(fd, "NULL\n");
283
284         return RESULT_SUCCESS;
285 }
286
287
288
289 static int handle_commandnummatches(int fd, int argc, char *argv[])
290 {
291         int matches = 0;
292
293         if (argc != 4)
294                 return RESULT_SHOWUSAGE;
295
296         matches = ast_cli_generatornummatches(argv[2], argv[3]);
297
298 #if 0
299         printf("Search for '%s' %s got '%d'\n", argv[2], argv[3], matches);
300 #endif
301         ast_cli(fd, "%d", matches);
302
303         return RESULT_SUCCESS;
304 }
305
306 static int handle_commandcomplete(int fd, int argc, char *argv[])
307 {
308         char *buf;
309 #if 0
310         printf("Search for %d args: '%s', '%s', '%s', '%s'\n", argc, argv[0], argv[1], argv[2], argv[3]);
311 #endif  
312         if (argc != 5)
313                 return RESULT_SHOWUSAGE;
314         buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
315 #if 0
316         printf("Search for '%s' %s %d got '%s'\n", argv[2], argv[3], atoi(argv[4]), buf);
317 #endif  
318         if (buf) {
319                 ast_cli(fd, buf);
320                 free(buf);
321         } else
322                 ast_cli(fd, "NULL\n");
323         return RESULT_SUCCESS;
324 }
325
326 static int handle_showchan(int fd, int argc, char *argv[])
327 {
328         struct ast_channel *c=NULL;
329         if (argc != 3)
330                 return RESULT_SHOWUSAGE;
331         c = ast_channel_walk(NULL);
332         while(c) {
333                 if (!strcasecmp(c->name, argv[2])) {
334                         ast_cli(fd, 
335         " -- General --\n"
336         "           Name: %s\n"
337         "           Type: %s\n"
338         "      Caller ID: %s\n"
339         "    DNID Digits: %s\n"
340         "          State: %s (%d)\n"
341         "          Rings: %d\n"
342         "   NativeFormat: %d\n"
343         "    WriteFormat: %d\n"
344         "     ReadFormat: %d\n"
345         "1st File Descriptor: %d\n"
346         "      Frames in: %d\n"
347         "     Frames out: %d\n"
348         " --   PBX   --\n"
349         "        Context: %s\n"
350         "      Extension: %s\n"
351         "       Priority: %d\n"
352         "    Application: %s\n"
353         "           Data: %s\n"
354         "          Stack: %d\n"
355         "    Blocking in: %s\n",
356         c->name, c->type, 
357         (c->callerid ? c->callerid : "(N/A)"),
358         (c->dnid ? c->dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings, c->nativeformats, c->writeformat, c->readformat,
359         c->fds[0], c->fin, c->fout, c->context, c->exten, c->priority, ( c->appl ? c->appl : "(N/A)" ),
360         ( c-> data ? (strlen(c->data) ? c->data : "(Empty)") : "(None)"),
361         c->stack, (c->blocking ? c->blockproc : "(Not Blocking)"));
362         
363                 break;
364                 }
365                 c = ast_channel_walk(c);
366         }
367         if (!c) 
368                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
369         return RESULT_SUCCESS;
370 }
371
372 static char *complete_ch(char *line, char *word, int pos, int state)
373 {
374         struct ast_channel *c;
375         int which=0;
376         c = ast_channel_walk(NULL);
377         while(c) {
378                 if (!strncasecmp(word, c->name, strlen(word))) {
379                         if (++which > state)
380                                 break;
381                 }
382                 c = ast_channel_walk(c);
383         }
384         return c ? strdup(c->name) : NULL;
385 }
386
387 static char *complete_fn(char *line, char *word, int pos, int state)
388 {
389         char *c;
390         char filename[256];
391         if (pos != 1)
392                 return NULL;
393         if (word[0] == '/')
394                 strncpy(filename, word, sizeof(filename)-1);
395         else
396                 snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_MODULE_DIR, word);
397         c = (char*)filename_completion_function(filename, state);
398         if (c && word[0] != '/')
399                 c += (strlen((char*)ast_config_AST_MODULE_DIR) + 1);
400         return c ? strdup(c) : c;
401 }
402
403 static int handle_help(int fd, int argc, char *argv[]);
404
405 static struct ast_cli_entry builtins[] = {
406         /* Keep alphabetized */
407         { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help },
408         { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
409         { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
410         { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
411         { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
412         { { "reload", NULL }, handle_reload, "Reload configuration", reload_help },
413         { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
414         { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch },
415         { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help },
416         { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
417         { { "show", "version", NULL }, handle_version, "Display version info", version_help },
418         { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch },
419         { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
420         { { NULL }, NULL, NULL, NULL }
421 };
422
423 static struct ast_cli_entry *find_cli(char *cmds[], int exact)
424 {
425         int x;
426         int y;
427         int match;
428         struct ast_cli_entry *e=NULL;
429         for (x=0;builtins[x].cmda[0];x++) {
430                 /* start optimistic */
431                 match = 1;
432                 for (y=0;match && cmds[y]; y++) {
433                         /* If there are no more words in the candidate command, then we're
434                            there.  */
435                         if (!builtins[x].cmda[y] && !exact)
436                                 break;
437                         /* If there are no more words in the command (and we're looking for
438                            an exact match) or there is a difference between the two words,
439                            then this is not a match */
440                         if (!builtins[x].cmda[y] || strcasecmp(builtins[x].cmda[y], cmds[y]))
441                                 match = 0;
442                 }
443                 /* If more words are needed to complete the command then this is not
444                    a candidate (unless we're looking for a really inexact answer  */
445                 if ((exact > -1) && builtins[x].cmda[y])
446                         match = 0;
447                 if (match)
448                         return &builtins[x];
449         }
450         for (e=helpers;e;e=e->next) {
451                 match = 1;
452                 for (y=0;match && cmds[y]; y++) {
453                         if (!e->cmda[y] && !exact)
454                                 break;
455                         if (!e->cmda[y] || strcasecmp(e->cmda[y], cmds[y]))
456                                 match = 0;
457                 }
458                 if ((exact > -1) && e->cmda[y])
459                         match = 0;
460                 if (match)
461                         break;
462         }
463         return e;
464 }
465
466 static void join(char *s, int len, char *w[])
467 {
468         int x;
469         /* Join words into a string */
470         strcpy(s, "");
471         for (x=0;w[x];x++) {
472                 if (x)
473                         strncat(s, " ", len - strlen(s));
474                 strncat(s, w[x], len - strlen(s));
475         }
476 }
477
478 static void join2(char *s, int len, char *w[])
479 {
480         int x;
481         /* Join words into a string */
482         strcpy(s, "");
483         for (x=0;w[x];x++) {
484                 strncat(s, w[x], len - strlen(s));
485         }
486 }
487
488 static char *find_best(char *argv[])
489 {
490         static char cmdline[80];
491         int x;
492         /* See how close we get, then print the  */
493         char *myargv[AST_MAX_CMD_LEN];
494         for (x=0;x<AST_MAX_CMD_LEN;x++)
495                 myargv[x]=NULL;
496         for (x=0;argv[x];x++) {
497                 myargv[x] = argv[x];
498                 if (!find_cli(myargv, -1))
499                         break;
500         }
501         join(cmdline, sizeof(cmdline), myargv);
502         return cmdline;
503 }
504
505 int ast_cli_unregister(struct ast_cli_entry *e)
506 {
507         struct ast_cli_entry *cur, *l=NULL;
508         ast_pthread_mutex_lock(&clilock);
509         cur = helpers;
510         while(cur) {
511                 if (e == cur) {
512                         if (e->inuse) {
513                                 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
514                         } else {
515                                 /* Rewrite */
516                                 if (l)
517                                         l->next = e->next;
518                                 else
519                                         helpers = e->next;
520                                 e->next = NULL;
521                                 break;
522                         }
523                 }
524                 l = cur;
525                 cur = cur->next;
526         }
527         ast_pthread_mutex_unlock(&clilock);
528         return 0;
529 }
530
531 int ast_cli_register(struct ast_cli_entry *e)
532 {
533         struct ast_cli_entry *cur, *l=NULL;
534         char fulle[80] ="", fulltst[80] ="";
535         static int len;
536         ast_pthread_mutex_lock(&clilock);
537         join2(fulle, sizeof(fulle), e->cmda);
538         if (find_cli(e->cmda, -1)) {
539                 ast_pthread_mutex_unlock(&clilock);
540                 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
541                 return -1;
542         }
543         cur = helpers;
544         while(cur) {
545                 join2(fulltst, sizeof(fulltst), cur->cmda);
546                 len = strlen(fulltst);
547                 if (strlen(fulle) < len)
548                         len = strlen(fulle);
549                 if (strncasecmp(fulle, fulltst, len) < 0) {
550                         if (l) {
551                                 e->next = l->next;
552                                 l->next = e;
553                         } else {
554                                 e->next = helpers;
555                                 helpers = e;
556                         }
557                         break;
558                 }
559                 l = cur;
560                 cur = cur->next;
561         }
562         if (!cur) {
563                 if (l)
564                         l->next = e;
565                 else
566                         helpers = e;
567                 e->next = NULL;
568         }
569         ast_pthread_mutex_unlock(&clilock);
570         return 0;
571 }
572
573 static int help_workhorse(int fd, char *match[])
574 {
575         char fullcmd1[80];
576         char fullcmd2[80];
577         char matchstr[80];
578         char *fullcmd;
579         struct ast_cli_entry *e, *e1, *e2;
580         e1 = builtins;
581         e2 = helpers;
582         if (match)
583                 join(matchstr, sizeof(matchstr), match);
584         while(e1->cmda[0] || e2) {
585                 if (e2)
586                         join(fullcmd2, sizeof(fullcmd2), e2->cmda);
587                 if (e1->cmda[0])
588                         join(fullcmd1, sizeof(fullcmd1), e1->cmda);
589                 if (!e1->cmda[0] || 
590                                 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
591                         /* Use e2 */
592                         e = e2;
593                         fullcmd = fullcmd2;
594                         /* Increment by going to next */
595                         e2 = e2->next;
596                 } else {
597                         /* Use e1 */
598                         e = e1;
599                         fullcmd = fullcmd1;
600                         e1++;
601                 }
602                 /* Hide commands that start with '_' */
603                 if (fullcmd[0] == '_')
604                         continue;
605                 if (match) {
606                         if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
607                                 continue;
608                         }
609                 }
610                 ast_cli(fd, "%20.20s   %s\n", fullcmd, e->summary);
611         }
612         return 0;
613 }
614
615 static int handle_help(int fd, int argc, char *argv[]) {
616         struct ast_cli_entry *e;
617         char fullcmd[80];
618         if ((argc < 1))
619                 return RESULT_SHOWUSAGE;
620         if (argc > 1) {
621                 e = find_cli(argv + 1, 1);
622                 if (e) 
623                         ast_cli(fd, e->usage);
624                 else {
625                         if (find_cli(argv + 1, -1)) {
626                                 return help_workhorse(fd, argv + 1);
627                         } else {
628                                 join(fullcmd, sizeof(fullcmd), argv+1);
629                                 ast_cli(fd, "No such command '%s'.\n", fullcmd);
630                         }
631                 }
632         } else {
633                 return help_workhorse(fd, NULL);
634         }
635         return RESULT_SUCCESS;
636 }
637
638 static char *parse_args(char *s, int *max, char *argv[])
639 {
640         char *dup, *cur;
641         int x=0;
642         int quoted=0;
643         int escaped=0;
644         int whitespace=1;
645
646         dup = strdup(s);
647         if (dup) {
648                 cur = dup;
649                 while(*s) {
650                         switch(*s) {
651                         case '"':
652                                 /* If it's escaped, put a literal quote */
653                                 if (escaped) 
654                                         goto normal;
655                                 else 
656                                         quoted = !quoted;
657                                 if (quoted && whitespace) {
658                                         /* If we're starting a quote, coming off white space start a new word, too */
659                                         argv[x++] = cur;
660                                         whitespace=0;
661                                 }
662                                 escaped = 0;
663                                 break;
664                         case ' ':
665                         case '\t':
666                                 if (!quoted && !escaped) {
667                                         /* If we're not quoted, mark this as whitespace, and
668                                            end the previous argument */
669                                         whitespace = 1;
670                                         *(cur++) = '\0';
671                                 } else
672                                         /* Otherwise, just treat it as anything else */ 
673                                         goto normal;
674                                 break;
675                         case '\\':
676                                 /* If we're escaped, print a literal, otherwise enable escaping */
677                                 if (escaped) {
678                                         goto normal;
679                                 } else {
680                                         escaped=1;
681                                 }
682                                 break;
683                         default:
684 normal:
685                                 if (whitespace) {
686                                         if (x >= AST_MAX_ARGS -1) {
687                                                 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
688                                                 break;
689                                         }
690                                         /* Coming off of whitespace, start the next argument */
691                                         argv[x++] = cur;
692                                         whitespace=0;
693                                 }
694                                 *(cur++) = *s;
695                                 escaped=0;
696                         }
697                         s++;
698                 }
699                 /* Null terminate */
700                 *(cur++) = '\0';
701                 argv[x] = NULL;
702                 *max = x;
703         }
704         return dup;
705 }
706
707 /* This returns the number of unique matches for the generator */
708 int ast_cli_generatornummatches(char *text, char *word)
709 {
710         int matches = 0, i = 0;
711         char *buf, *oldbuf;
712
713
714         while ( (buf = ast_cli_generator(text, word, i)) ) {
715                 if (++i > 1 && strcmp(buf,oldbuf) == 0)  
716                                 continue;
717                 oldbuf = buf;
718                 matches++;
719         }
720
721         return matches;
722 }
723
724 char **ast_cli_completion_matches(char *text, char *word)
725 {
726         char **match_list = NULL, *retstr, *prevstr;
727         size_t match_list_len, max_equal, which, i;
728         int matches = 0;
729
730         match_list_len = 1;
731         while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
732                 if (matches + 1 >= match_list_len) {
733                         match_list_len <<= 1;
734                         match_list = realloc(match_list, match_list_len * sizeof(char *));
735                 }
736                 match_list[++matches] = retstr;
737         }
738
739         if (!match_list)
740                 return (char **) NULL;
741
742         which = 2;
743         prevstr = match_list[1];
744         max_equal = strlen(prevstr);
745         for (; which <= matches; which++) {
746                 for (i = 0; i < max_equal && prevstr[i] == match_list[which][i]; i++)
747                         continue;
748                 max_equal = i;
749         }
750
751         retstr = malloc(max_equal + 1);
752         (void) strncpy(retstr, match_list[1], max_equal);
753         retstr[max_equal] = '\0';
754         match_list[0] = retstr;
755
756         if (matches + 1 >= match_list_len)
757                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
758         match_list[matches + 1] = (char *) NULL;
759
760         return (match_list);
761 }
762
763 static char *__ast_cli_generator(char *text, char *word, int state, int lock)
764 {
765         char *argv[AST_MAX_ARGS];
766         struct ast_cli_entry *e, *e1, *e2;
767         int x;
768         int matchnum=0;
769         char *dup, *res;
770         char fullcmd1[80];
771         char fullcmd2[80];
772         char matchstr[80];
773         char *fullcmd;
774
775         if ((dup = parse_args(text, &x, argv))) {
776                 join(matchstr, sizeof(matchstr), argv);
777                 if (lock)
778                         ast_pthread_mutex_lock(&clilock);
779                 e1 = builtins;
780                 e2 = helpers;
781                 while(e1->cmda[0] || e2) {
782                         if (e2)
783                                 join(fullcmd2, sizeof(fullcmd2), e2->cmda);
784                         if (e1->cmda[0])
785                                 join(fullcmd1, sizeof(fullcmd1), e1->cmda);
786                         if (!e1->cmda[0] || 
787                                         (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
788                                 /* Use e2 */
789                                 e = e2;
790                                 fullcmd = fullcmd2;
791                                 /* Increment by going to next */
792                                 e2 = e2->next;
793                         } else {
794                                 /* Use e1 */
795                                 e = e1;
796                                 fullcmd = fullcmd1;
797                                 e1++;
798                         }
799                         if ((fullcmd[0] != '_') && !strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
800                                 /* We contain the first part of one or more commands */
801                                 matchnum++;
802                                 if (matchnum > state) {
803                                         /* Now, what we're supposed to return is the next word... */
804                                         if (strlen(word)) {
805                                                 res = e->cmda[x-1];
806                                         } else {
807                                                 res = e->cmda[x];
808                                         }
809                                         if (res) {
810                                                 if (lock)
811                                                         ast_pthread_mutex_unlock(&clilock);
812                                                 return res ? strdup(res) : NULL;
813                                         }
814                                 }
815                         }
816                         if (e->generator && !strncasecmp(matchstr, fullcmd, strlen(fullcmd))) {
817                                 /* We have a command in its entirity within us -- theoretically only one
818                                    command can have this occur */
819                                 fullcmd = e->generator(text, word, (strlen(word) ? (x - 1) : (x)), state);
820                                 if (lock)
821                                         ast_pthread_mutex_unlock(&clilock);
822                                 return fullcmd;
823                         }
824                         
825                 }
826                 if (lock)
827                         ast_pthread_mutex_unlock(&clilock);
828                 free(dup);
829         }
830         return NULL;
831 }
832
833 char *ast_cli_generator(char *text, char *word, int state)
834 {
835         return __ast_cli_generator(text, word, state, 1);
836 }
837
838 int ast_cli_command(int fd, char *s)
839 {
840         char *argv[AST_MAX_ARGS];
841         struct ast_cli_entry *e;
842         int x;
843         char *dup;
844         x = AST_MAX_ARGS;
845         if ((dup = parse_args(s, &x, argv))) {
846                 /* We need at least one entry, or ignore */
847                 if (x > 0) {
848                         ast_pthread_mutex_lock(&clilock);
849                         e = find_cli(argv, 0);
850                         if (e)
851                                 e->inuse++;
852                         ast_pthread_mutex_unlock(&clilock);
853                         if (e) {
854                                 switch(e->handler(fd, x, argv)) {
855                                 case RESULT_SHOWUSAGE:
856                                         ast_cli(fd, e->usage);
857                                         break;
858                                 default:
859                                 }
860                         } else 
861                                 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
862                         if (e) {
863                                 ast_pthread_mutex_lock(&clilock);
864                                 e->inuse--;
865                                 ast_pthread_mutex_unlock(&clilock);
866                         }
867                 }
868                 free(dup);
869         } else {
870                 ast_log(LOG_WARNING, "Out of memory\n");        
871                 return -1;
872         }
873         return 0;
874 }