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