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