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