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