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