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