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