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