898c95555bba8b06aa3872cc9f88050e1da32913
[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         struct timeval now;
527         long elapsed_seconds=0;
528         if (argc != 3)
529                 return RESULT_SHOWUSAGE;
530         gettimeofday(&now, NULL);
531         c = ast_channel_walk_locked(NULL);
532         while(c) {
533                 if (!strcasecmp(c->name, argv[2])) {
534                         if(c->cdr) {
535                                 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
536                         }
537                         ast_cli(fd, 
538         " -- General --\n"
539         "           Name: %s\n"
540         "           Type: %s\n"
541         "       UniqueID: %s\n"
542         "      Caller ID: %s\n"
543         "    DNID Digits: %s\n"
544         "          State: %s (%d)\n"
545         "          Rings: %d\n"
546         "   NativeFormat: %d\n"
547         "    WriteFormat: %d\n"
548         "     ReadFormat: %d\n"
549         "1st File Descriptor: %d\n"
550         "      Frames in: %d%s\n"
551         "     Frames out: %d%s\n"
552         " Time to Hangup: %ld\n"
553         "Elapsed Seconds: %ld\n"
554         " --   PBX   --\n"
555         "        Context: %s\n"
556         "      Extension: %s\n"
557         "       Priority: %d\n"
558         "     Call Group: %d\n"
559         "   Pickup Group: %d\n"
560         "    Application: %s\n"
561         "           Data: %s\n"
562         "          Stack: %d\n"
563         "    Blocking in: %s\n",
564         c->name, c->type, c->uniqueid,
565         (c->callerid ? c->callerid : "(N/A)"),
566         (c->dnid ? c->dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings, c->nativeformats, c->writeformat, c->readformat,
567         c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
568         c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", (long)c->whentohangup,
569         (long)elapsed_seconds, 
570         c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
571         ( c-> data ? (!ast_strlen_zero(c->data) ? c->data : "(Empty)") : "(None)"),
572         c->stack, (c->blocking ? c->blockproc : "(Not Blocking)"));
573                 ast_mutex_unlock(&c->lock);
574                 break;
575                 }
576                 ast_mutex_unlock(&c->lock);
577                 c = ast_channel_walk_locked(c);
578         }
579         if (!c) 
580                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
581         return RESULT_SUCCESS;
582 }
583
584 static char *complete_ch_helper(char *line, char *word, int pos, int state, int rpos)
585 {
586         struct ast_channel *c;
587         int which=0;
588         char *ret;
589         if (pos != rpos)
590                 return NULL;
591         c = ast_channel_walk_locked(NULL);
592         while(c) {
593                 if (!strncasecmp(word, c->name, strlen(word))) {
594                         if (++which > state)
595                                 break;
596                 }
597                 ast_mutex_unlock(&c->lock);
598                 c = ast_channel_walk_locked(c);
599         }
600         if (c) {
601                 ret = strdup(c->name);
602                 ast_mutex_unlock(&c->lock);
603         } else
604                 ret = NULL;
605         return ret;
606 }
607
608 static char *complete_ch_3(char *line, char *word, int pos, int state)
609 {
610         return complete_ch_helper(line, word, pos, state, 2);
611 }
612
613 static char *complete_ch_4(char *line, char *word, int pos, int state)
614 {
615         return complete_ch_helper(line, word, pos, state, 3);
616 }
617
618 static char *complete_fn(char *line, char *word, int pos, int state)
619 {
620         char *c;
621         char filename[256];
622         if (pos != 1)
623                 return NULL;
624         if (word[0] == '/')
625                 strncpy(filename, word, sizeof(filename)-1);
626         else
627                 snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_MODULE_DIR, word);
628         c = (char*)filename_completion_function(filename, state);
629         if (c && word[0] != '/')
630                 c += (strlen((char*)ast_config_AST_MODULE_DIR) + 1);
631         return c ? strdup(c) : c;
632 }
633
634 static int handle_help(int fd, int argc, char *argv[]);
635
636 static struct ast_cli_entry builtins[] = {
637         /* Keep alphabetized, with longer matches first (example: abcd before abc) */
638         { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
639         { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
640         { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
641         { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch_3 },
642         { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help },
643         { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
644         { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch_4 },
645         { { "reload", NULL }, handle_reload, "Reload configuration", reload_help },
646         { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
647         { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help },
648         { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch_3 },
649         { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
650         { { "show", "uptime", NULL }, handle_showuptime, "Show uptime information", modlist_help },
651         { { "show", "version", NULL }, handle_version, "Display version info", version_help },
652         { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch_3 },
653         { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
654         { { NULL }, NULL, NULL, NULL }
655 };
656
657 static struct ast_cli_entry *find_cli(char *cmds[], int exact)
658 {
659         int x;
660         int y;
661         int match;
662         struct ast_cli_entry *e=NULL;
663         for (x=0;builtins[x].cmda[0];x++) {
664                 /* start optimistic */
665                 match = 1;
666                 for (y=0;match && cmds[y]; y++) {
667                         /* If there are no more words in the candidate command, then we're
668                            there.  */
669                         if (!builtins[x].cmda[y] && !exact)
670                                 break;
671                         /* If there are no more words in the command (and we're looking for
672                            an exact match) or there is a difference between the two words,
673                            then this is not a match */
674                         if (!builtins[x].cmda[y] || strcasecmp(builtins[x].cmda[y], cmds[y]))
675                                 match = 0;
676                 }
677                 /* If more words are needed to complete the command then this is not
678                    a candidate (unless we're looking for a really inexact answer  */
679                 if ((exact > -1) && builtins[x].cmda[y])
680                         match = 0;
681                 if (match)
682                         return &builtins[x];
683         }
684         for (e=helpers;e;e=e->next) {
685                 match = 1;
686                 for (y=0;match && cmds[y]; y++) {
687                         if (!e->cmda[y] && !exact)
688                                 break;
689                         if (!e->cmda[y] || strcasecmp(e->cmda[y], cmds[y]))
690                                 match = 0;
691                 }
692                 if ((exact > -1) && e->cmda[y])
693                         match = 0;
694                 if (match)
695                         break;
696         }
697         return e;
698 }
699
700 static void join(char *dest, size_t destsize, char *w[])
701 {
702         int x;
703         /* Join words into a string */
704         if (!dest || destsize < 1) {
705                 return;
706         }
707         dest[0] = '\0';
708         for (x=0;w[x];x++) {
709                 if (x)
710                         strncat(dest, " ", destsize - strlen(dest) - 1);
711                 strncat(dest, w[x], destsize - strlen(dest) - 1);
712         }
713 }
714
715 static void join2(char *dest, size_t destsize, char *w[])
716 {
717         int x;
718         /* Join words into a string */
719         if (!dest || destsize < 1) {
720                 return;
721         }
722         dest[0] = '\0';
723         for (x=0;w[x];x++) {
724                 strncat(dest, w[x], destsize - strlen(dest) - 1);
725         }
726 }
727
728 static char *find_best(char *argv[])
729 {
730         static char cmdline[80];
731         int x;
732         /* See how close we get, then print the  */
733         char *myargv[AST_MAX_CMD_LEN];
734         for (x=0;x<AST_MAX_CMD_LEN;x++)
735                 myargv[x]=NULL;
736         for (x=0;argv[x];x++) {
737                 myargv[x] = argv[x];
738                 if (!find_cli(myargv, -1))
739                         break;
740         }
741         join(cmdline, sizeof(cmdline), myargv);
742         return cmdline;
743 }
744
745 int ast_cli_unregister(struct ast_cli_entry *e)
746 {
747         struct ast_cli_entry *cur, *l=NULL;
748         ast_mutex_lock(&clilock);
749         cur = helpers;
750         while(cur) {
751                 if (e == cur) {
752                         if (e->inuse) {
753                                 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
754                         } else {
755                                 /* Rewrite */
756                                 if (l)
757                                         l->next = e->next;
758                                 else
759                                         helpers = e->next;
760                                 e->next = NULL;
761                                 break;
762                         }
763                 }
764                 l = cur;
765                 cur = cur->next;
766         }
767         ast_mutex_unlock(&clilock);
768         return 0;
769 }
770
771 int ast_cli_register(struct ast_cli_entry *e)
772 {
773         struct ast_cli_entry *cur, *l=NULL;
774         char fulle[80] ="", fulltst[80] ="";
775         static int len;
776         ast_mutex_lock(&clilock);
777         join2(fulle, sizeof(fulle), e->cmda);
778         if (find_cli(e->cmda, -1)) {
779                 ast_mutex_unlock(&clilock);
780                 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
781                 return -1;
782         }
783         cur = helpers;
784         while(cur) {
785                 join2(fulltst, sizeof(fulltst), cur->cmda);
786                 len = strlen(fulltst);
787                 if (strlen(fulle) < len)
788                         len = strlen(fulle);
789                 if (strncasecmp(fulle, fulltst, len) < 0) {
790                         if (l) {
791                                 e->next = l->next;
792                                 l->next = e;
793                         } else {
794                                 e->next = helpers;
795                                 helpers = e;
796                         }
797                         break;
798                 }
799                 l = cur;
800                 cur = cur->next;
801         }
802         if (!cur) {
803                 if (l)
804                         l->next = e;
805                 else
806                         helpers = e;
807                 e->next = NULL;
808         }
809         ast_mutex_unlock(&clilock);
810         return 0;
811 }
812
813 static int help_workhorse(int fd, char *match[])
814 {
815         char fullcmd1[80];
816         char fullcmd2[80];
817         char matchstr[80];
818         char *fullcmd;
819         struct ast_cli_entry *e, *e1, *e2;
820         e1 = builtins;
821         e2 = helpers;
822         if (match)
823                 join(matchstr, sizeof(matchstr), match);
824         while(e1->cmda[0] || e2) {
825                 if (e2)
826                         join(fullcmd2, sizeof(fullcmd2), e2->cmda);
827                 if (e1->cmda[0])
828                         join(fullcmd1, sizeof(fullcmd1), e1->cmda);
829                 if (!e1->cmda[0] || 
830                                 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
831                         /* Use e2 */
832                         e = e2;
833                         fullcmd = fullcmd2;
834                         /* Increment by going to next */
835                         e2 = e2->next;
836                 } else {
837                         /* Use e1 */
838                         e = e1;
839                         fullcmd = fullcmd1;
840                         e1++;
841                 }
842                 /* Hide commands that start with '_' */
843                 if (fullcmd[0] == '_')
844                         continue;
845                 if (match) {
846                         if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
847                                 continue;
848                         }
849                 }
850                 ast_cli(fd, "%25.25s  %s\n", fullcmd, e->summary);
851         }
852         return 0;
853 }
854
855 static int handle_help(int fd, int argc, char *argv[]) {
856         struct ast_cli_entry *e;
857         char fullcmd[80];
858         if ((argc < 1))
859                 return RESULT_SHOWUSAGE;
860         if (argc > 1) {
861                 e = find_cli(argv + 1, 1);
862                 if (e) 
863                         ast_cli(fd, e->usage);
864                 else {
865                         if (find_cli(argv + 1, -1)) {
866                                 return help_workhorse(fd, argv + 1);
867                         } else {
868                                 join(fullcmd, sizeof(fullcmd), argv+1);
869                                 ast_cli(fd, "No such command '%s'.\n", fullcmd);
870                         }
871                 }
872         } else {
873                 return help_workhorse(fd, NULL);
874         }
875         return RESULT_SUCCESS;
876 }
877
878 static char *parse_args(char *s, int *max, char *argv[])
879 {
880         char *dup, *cur;
881         int x=0;
882         int quoted=0;
883         int escaped=0;
884         int whitespace=1;
885
886         dup = strdup(s);
887         if (dup) {
888                 cur = dup;
889                 while(*s) {
890                         switch(*s) {
891                         case '"':
892                                 /* If it's escaped, put a literal quote */
893                                 if (escaped) 
894                                         goto normal;
895                                 else 
896                                         quoted = !quoted;
897                                 if (quoted && whitespace) {
898                                         /* If we're starting a quote, coming off white space start a new word, too */
899                                         argv[x++] = cur;
900                                         whitespace=0;
901                                 }
902                                 escaped = 0;
903                                 break;
904                         case ' ':
905                         case '\t':
906                                 if (!quoted && !escaped) {
907                                         /* If we're not quoted, mark this as whitespace, and
908                                            end the previous argument */
909                                         whitespace = 1;
910                                         *(cur++) = '\0';
911                                 } else
912                                         /* Otherwise, just treat it as anything else */ 
913                                         goto normal;
914                                 break;
915                         case '\\':
916                                 /* If we're escaped, print a literal, otherwise enable escaping */
917                                 if (escaped) {
918                                         goto normal;
919                                 } else {
920                                         escaped=1;
921                                 }
922                                 break;
923                         default:
924 normal:
925                                 if (whitespace) {
926                                         if (x >= AST_MAX_ARGS -1) {
927                                                 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
928                                                 break;
929                                         }
930                                         /* Coming off of whitespace, start the next argument */
931                                         argv[x++] = cur;
932                                         whitespace=0;
933                                 }
934                                 *(cur++) = *s;
935                                 escaped=0;
936                         }
937                         s++;
938                 }
939                 /* Null terminate */
940                 *(cur++) = '\0';
941                 argv[x] = NULL;
942                 *max = x;
943         }
944         return dup;
945 }
946
947 /* This returns the number of unique matches for the generator */
948 int ast_cli_generatornummatches(char *text, char *word)
949 {
950         int matches = 0, i = 0;
951         char *buf, *oldbuf = NULL;
952
953
954         while ( (buf = ast_cli_generator(text, word, i)) ) {
955                 if (++i > 1 && strcmp(buf,oldbuf) == 0)  {
956                                 continue;
957                 }
958                 oldbuf = buf;
959                 matches++;
960         }
961
962         return matches;
963 }
964
965 char **ast_cli_completion_matches(char *text, char *word)
966 {
967         char **match_list = NULL, *retstr, *prevstr;
968         size_t match_list_len, max_equal, which, i;
969         int matches = 0;
970
971         match_list_len = 1;
972         while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
973                 if (matches + 1 >= match_list_len) {
974                         match_list_len <<= 1;
975                         match_list = realloc(match_list, match_list_len * sizeof(char *));
976                 }
977                 match_list[++matches] = retstr;
978         }
979
980         if (!match_list)
981                 return (char **) NULL;
982
983         which = 2;
984         prevstr = match_list[1];
985         max_equal = strlen(prevstr);
986         for (; which <= matches; which++) {
987                 for (i = 0; i < max_equal && prevstr[i] == match_list[which][i]; i++)
988                         continue;
989                 max_equal = i;
990         }
991
992         retstr = malloc(max_equal + 1);
993         (void) strncpy(retstr, match_list[1], max_equal);
994         retstr[max_equal] = '\0';
995         match_list[0] = retstr;
996
997         if (matches + 1 >= match_list_len)
998                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
999         match_list[matches + 1] = (char *) NULL;
1000
1001         return (match_list);
1002 }
1003
1004 static char *__ast_cli_generator(char *text, char *word, int state, int lock)
1005 {
1006         char *argv[AST_MAX_ARGS];
1007         struct ast_cli_entry *e, *e1, *e2;
1008         int x;
1009         int matchnum=0;
1010         char *dup, *res;
1011         char fullcmd1[80];
1012         char fullcmd2[80];
1013         char matchstr[80];
1014         char *fullcmd;
1015
1016         if ((dup = parse_args(text, &x, argv))) {
1017                 join(matchstr, sizeof(matchstr), argv);
1018                 if (lock)
1019                         ast_mutex_lock(&clilock);
1020                 e1 = builtins;
1021                 e2 = helpers;
1022                 while(e1->cmda[0] || e2) {
1023                         if (e2)
1024                                 join(fullcmd2, sizeof(fullcmd2), e2->cmda);
1025                         if (e1->cmda[0])
1026                                 join(fullcmd1, sizeof(fullcmd1), e1->cmda);
1027                         if (!e1->cmda[0] || 
1028                                         (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
1029                                 /* Use e2 */
1030                                 e = e2;
1031                                 fullcmd = fullcmd2;
1032                                 /* Increment by going to next */
1033                                 e2 = e2->next;
1034                         } else {
1035                                 /* Use e1 */
1036                                 e = e1;
1037                                 fullcmd = fullcmd1;
1038                                 e1++;
1039                         }
1040                         if ((fullcmd[0] != '_') && !strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1041                                 /* We contain the first part of one or more commands */
1042                                 matchnum++;
1043                                 if (matchnum > state) {
1044                                         /* Now, what we're supposed to return is the next word... */
1045                                         if (!ast_strlen_zero(word) && x>0) {
1046                                                 res = e->cmda[x-1];
1047                                         } else {
1048                                                 res = e->cmda[x];
1049                                         }
1050                                         if (res) {
1051                                                 if (lock)
1052                                                         ast_mutex_unlock(&clilock);
1053                                                 free(dup);
1054                                                 return res ? strdup(res) : NULL;
1055                                         }
1056                                 }
1057                         }
1058                         if (e->generator && !strncasecmp(matchstr, fullcmd, strlen(fullcmd))) {
1059                                 /* We have a command in its entirity within us -- theoretically only one
1060                                    command can have this occur */
1061                                 fullcmd = e->generator(matchstr, word, (!ast_strlen_zero(word) ? (x - 1) : (x)), state);
1062                                 if (lock)
1063                                         ast_mutex_unlock(&clilock);
1064                                 free(dup);
1065                                 return fullcmd;
1066                         }
1067                         
1068                 }
1069                 if (lock)
1070                         ast_mutex_unlock(&clilock);
1071                 free(dup);
1072         }
1073         return NULL;
1074 }
1075
1076 char *ast_cli_generator(char *text, char *word, int state)
1077 {
1078         return __ast_cli_generator(text, word, state, 1);
1079 }
1080
1081 int ast_cli_command(int fd, char *s)
1082 {
1083         char *argv[AST_MAX_ARGS];
1084         struct ast_cli_entry *e;
1085         int x;
1086         char *dup;
1087         x = AST_MAX_ARGS;
1088         if ((dup = parse_args(s, &x, argv))) {
1089                 /* We need at least one entry, or ignore */
1090                 if (x > 0) {
1091                         ast_mutex_lock(&clilock);
1092                         e = find_cli(argv, 0);
1093                         if (e)
1094                                 e->inuse++;
1095                         ast_mutex_unlock(&clilock);
1096                         if (e) {
1097                                 switch(e->handler(fd, x, argv)) {
1098                                 case RESULT_SHOWUSAGE:
1099                                         ast_cli(fd, e->usage);
1100                                         break;
1101                                 }
1102                         } else 
1103                                 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1104                         if (e) {
1105                                 ast_mutex_lock(&clilock);
1106                                 e->inuse--;
1107                                 ast_mutex_unlock(&clilock);
1108                         }
1109                 }
1110                 free(dup);
1111         } else {
1112                 ast_log(LOG_WARNING, "Out of memory\n");        
1113                 return -1;
1114         }
1115         return 0;
1116 }