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