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