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