Fix CLI to report "N/A" when appropriate for time, chan_features updates, ALSA and...
[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         char cdrtime[256];
637         long elapsed_seconds=0;
638         int hour=0, min=0, sec=0;
639         if (argc != 3)
640                 return RESULT_SHOWUSAGE;
641         gettimeofday(&now, NULL);
642         c = ast_channel_walk_locked(NULL);
643         while(c) {
644                 if (!strcasecmp(c->name, argv[2])) {
645                         if(c->cdr) {
646                                 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
647                                 hour = elapsed_seconds / 3600;
648                                 min = (elapsed_seconds % 3600) / 60;
649                                 sec = elapsed_seconds % 60;
650                                 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
651                         } else
652                                 strncpy(cdrtime, "N/A", sizeof(cdrtime) -1);
653                         ast_cli(fd, 
654         " -- General --\n"
655         "           Name: %s\n"
656         "           Type: %s\n"
657         "       UniqueID: %s\n"
658         "      Caller ID: %s\n"
659         " Caller ID Name: %s\n"
660         "    DNID Digits: %s\n"
661         "          State: %s (%d)\n"
662         "          Rings: %d\n"
663         "   NativeFormat: %d\n"
664         "    WriteFormat: %d\n"
665         "     ReadFormat: %d\n"
666         "1st File Descriptor: %d\n"
667         "      Frames in: %d%s\n"
668         "     Frames out: %d%s\n"
669         " Time to Hangup: %ld\n"
670         "   Elapsed Time: %s\n"
671         " --   PBX   --\n"
672         "        Context: %s\n"
673         "      Extension: %s\n"
674         "       Priority: %d\n"
675         "     Call Group: %d\n"
676         "   Pickup Group: %d\n"
677         "    Application: %s\n"
678         "           Data: %s\n"
679         "    Blocking in: %s\n",
680         c->name, c->type, c->uniqueid,
681         (c->cid.cid_num ? c->cid.cid_num : "(N/A)"),
682         (c->cid.cid_name ? c->cid.cid_name : "(N/A)"),
683         (c->cid.cid_dnid ? c->cid.cid_dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings, c->nativeformats, c->writeformat, c->readformat,
684         c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
685         c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", (long)c->whentohangup,
686         cdrtime,
687         c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
688         ( c-> data ? (!ast_strlen_zero(c->data) ? c->data : "(Empty)") : "(None)"),
689         (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
690                         if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
691                                 ast_cli(fd,"Variables:\n%s\n",buf);
692
693                 ast_mutex_unlock(&c->lock);
694                 break;
695                 }
696                 ast_mutex_unlock(&c->lock);
697                 c = ast_channel_walk_locked(c);
698         }
699         if (!c) 
700                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
701         return RESULT_SUCCESS;
702 }
703
704 static char *complete_ch_helper(char *line, char *word, int pos, int state, int rpos)
705 {
706         struct ast_channel *c;
707         int which=0;
708         char *ret;
709         if (pos != rpos)
710                 return NULL;
711         c = ast_channel_walk_locked(NULL);
712         while(c) {
713                 if (!strncasecmp(word, c->name, strlen(word))) {
714                         if (++which > state)
715                                 break;
716                 }
717                 ast_mutex_unlock(&c->lock);
718                 c = ast_channel_walk_locked(c);
719         }
720         if (c) {
721                 ret = strdup(c->name);
722                 ast_mutex_unlock(&c->lock);
723         } else
724                 ret = NULL;
725         return ret;
726 }
727
728 static char *complete_ch_3(char *line, char *word, int pos, int state)
729 {
730         return complete_ch_helper(line, word, pos, state, 2);
731 }
732
733 static char *complete_ch_4(char *line, char *word, int pos, int state)
734 {
735         return complete_ch_helper(line, word, pos, state, 3);
736 }
737
738 static char *complete_mod_2(char *line, char *word, int pos, int state)
739 {
740         return ast_module_helper(line, word, pos, state, 1, 1);
741 }
742
743 static char *complete_mod_4(char *line, char *word, int pos, int state)
744 {
745         return ast_module_helper(line, word, pos, state, 3, 0);
746 }
747
748 static char *complete_fn(char *line, char *word, int pos, int state)
749 {
750         char *c;
751         char filename[256];
752         if (pos != 1)
753                 return NULL;
754         if (word[0] == '/')
755                 strncpy(filename, word, sizeof(filename)-1);
756         else
757                 snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_MODULE_DIR, word);
758         c = (char*)filename_completion_function(filename, state);
759         if (c && word[0] != '/')
760                 c += (strlen((char*)ast_config_AST_MODULE_DIR) + 1);
761         return c ? strdup(c) : c;
762 }
763
764 static int handle_help(int fd, int argc, char *argv[]);
765
766 static struct ast_cli_entry builtins[] = {
767         /* Keep alphabetized, with longer matches first (example: abcd before abc) */
768         { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
769         { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
770         { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
771         { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch_3 },
772         { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help },
773         { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
774         { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch_4 },
775         { { "reload", NULL }, handle_reload, "Reload configuration", reload_help, complete_mod_2 },
776         { { "set", "debug", NULL }, handle_set_debug, "Set level of debug chattiness", set_debug_help },
777         { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
778         { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help },
779         { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch_3 },
780         { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
781         { { "show", "modules", "like", NULL }, handle_modlist, "List modules and info", modlist_help, complete_mod_4 },
782         { { "show", "uptime", NULL }, handle_showuptime, "Show uptime information", modlist_help },
783         { { "show", "version", NULL }, handle_version, "Display version info", version_help },
784         { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch_3 },
785         { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
786         { { NULL }, NULL, NULL, NULL }
787 };
788
789 static struct ast_cli_entry *find_cli(char *cmds[], int exact)
790 {
791         int x;
792         int y;
793         int match;
794         struct ast_cli_entry *e=NULL;
795         for (x=0;builtins[x].cmda[0];x++) {
796                 /* start optimistic */
797                 match = 1;
798                 for (y=0;match && cmds[y]; y++) {
799                         /* If there are no more words in the candidate command, then we're
800                            there.  */
801                         if (!builtins[x].cmda[y] && !exact)
802                                 break;
803                         /* If there are no more words in the command (and we're looking for
804                            an exact match) or there is a difference between the two words,
805                            then this is not a match */
806                         if (!builtins[x].cmda[y] || strcasecmp(builtins[x].cmda[y], cmds[y]))
807                                 match = 0;
808                 }
809                 /* If more words are needed to complete the command then this is not
810                    a candidate (unless we're looking for a really inexact answer  */
811                 if ((exact > -1) && builtins[x].cmda[y])
812                         match = 0;
813                 if (match)
814                         return &builtins[x];
815         }
816         for (e=helpers;e;e=e->next) {
817                 match = 1;
818                 for (y=0;match && cmds[y]; y++) {
819                         if (!e->cmda[y] && !exact)
820                                 break;
821                         if (!e->cmda[y] || strcasecmp(e->cmda[y], cmds[y]))
822                                 match = 0;
823                 }
824                 if ((exact > -1) && e->cmda[y])
825                         match = 0;
826                 if (match)
827                         break;
828         }
829         return e;
830 }
831
832 static void join(char *dest, size_t destsize, char *w[])
833 {
834         int x;
835         /* Join words into a string */
836         if (!dest || destsize < 1) {
837                 return;
838         }
839         dest[0] = '\0';
840         for (x=0;w[x];x++) {
841                 if (x)
842                         strncat(dest, " ", destsize - strlen(dest) - 1);
843                 strncat(dest, w[x], destsize - strlen(dest) - 1);
844         }
845 }
846
847 static void join2(char *dest, size_t destsize, char *w[])
848 {
849         int x;
850         /* Join words into a string */
851         if (!dest || destsize < 1) {
852                 return;
853         }
854         dest[0] = '\0';
855         for (x=0;w[x];x++) {
856                 strncat(dest, w[x], destsize - strlen(dest) - 1);
857         }
858 }
859
860 static char *find_best(char *argv[])
861 {
862         static char cmdline[80];
863         int x;
864         /* See how close we get, then print the  */
865         char *myargv[AST_MAX_CMD_LEN];
866         for (x=0;x<AST_MAX_CMD_LEN;x++)
867                 myargv[x]=NULL;
868         for (x=0;argv[x];x++) {
869                 myargv[x] = argv[x];
870                 if (!find_cli(myargv, -1))
871                         break;
872         }
873         join(cmdline, sizeof(cmdline), myargv);
874         return cmdline;
875 }
876
877 int ast_cli_unregister(struct ast_cli_entry *e)
878 {
879         struct ast_cli_entry *cur, *l=NULL;
880         ast_mutex_lock(&clilock);
881         cur = helpers;
882         while(cur) {
883                 if (e == cur) {
884                         if (e->inuse) {
885                                 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
886                         } else {
887                                 /* Rewrite */
888                                 if (l)
889                                         l->next = e->next;
890                                 else
891                                         helpers = e->next;
892                                 e->next = NULL;
893                                 break;
894                         }
895                 }
896                 l = cur;
897                 cur = cur->next;
898         }
899         ast_mutex_unlock(&clilock);
900         return 0;
901 }
902
903 int ast_cli_register(struct ast_cli_entry *e)
904 {
905         struct ast_cli_entry *cur, *l=NULL;
906         char fulle[80] ="", fulltst[80] ="";
907         static int len;
908         ast_mutex_lock(&clilock);
909         join2(fulle, sizeof(fulle), e->cmda);
910         if (find_cli(e->cmda, -1)) {
911                 ast_mutex_unlock(&clilock);
912                 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
913                 return -1;
914         }
915         cur = helpers;
916         while(cur) {
917                 join2(fulltst, sizeof(fulltst), cur->cmda);
918                 len = strlen(fulltst);
919                 if (strlen(fulle) < len)
920                         len = strlen(fulle);
921                 if (strncasecmp(fulle, fulltst, len) < 0) {
922                         if (l) {
923                                 e->next = l->next;
924                                 l->next = e;
925                         } else {
926                                 e->next = helpers;
927                                 helpers = e;
928                         }
929                         break;
930                 }
931                 l = cur;
932                 cur = cur->next;
933         }
934         if (!cur) {
935                 if (l)
936                         l->next = e;
937                 else
938                         helpers = e;
939                 e->next = NULL;
940         }
941         ast_mutex_unlock(&clilock);
942         return 0;
943 }
944
945 static int help_workhorse(int fd, char *match[])
946 {
947         char fullcmd1[80] = "";
948         char fullcmd2[80] = "";
949         char matchstr[80];
950         char *fullcmd = NULL;
951         struct ast_cli_entry *e, *e1, *e2;
952         e1 = builtins;
953         e2 = helpers;
954         if (match)
955                 join(matchstr, sizeof(matchstr), match);
956         while(e1->cmda[0] || e2) {
957                 if (e2)
958                         join(fullcmd2, sizeof(fullcmd2), e2->cmda);
959                 if (e1->cmda[0])
960                         join(fullcmd1, sizeof(fullcmd1), e1->cmda);
961                 if (!e1->cmda[0] || 
962                                 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
963                         /* Use e2 */
964                         e = e2;
965                         fullcmd = fullcmd2;
966                         /* Increment by going to next */
967                         e2 = e2->next;
968                 } else {
969                         /* Use e1 */
970                         e = e1;
971                         fullcmd = fullcmd1;
972                         e1++;
973                 }
974                 /* Hide commands that start with '_' */
975                 if (fullcmd[0] == '_')
976                         continue;
977                 if (match) {
978                         if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
979                                 continue;
980                         }
981                 }
982                 ast_cli(fd, "%25.25s  %s\n", fullcmd, e->summary);
983         }
984         return 0;
985 }
986
987 static int handle_help(int fd, int argc, char *argv[]) {
988         struct ast_cli_entry *e;
989         char fullcmd[80];
990         if ((argc < 1))
991                 return RESULT_SHOWUSAGE;
992         if (argc > 1) {
993                 e = find_cli(argv + 1, 1);
994                 if (e) 
995                         ast_cli(fd, e->usage);
996                 else {
997                         if (find_cli(argv + 1, -1)) {
998                                 return help_workhorse(fd, argv + 1);
999                         } else {
1000                                 join(fullcmd, sizeof(fullcmd), argv+1);
1001                                 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1002                         }
1003                 }
1004         } else {
1005                 return help_workhorse(fd, NULL);
1006         }
1007         return RESULT_SUCCESS;
1008 }
1009
1010 static char *parse_args(char *s, int *max, char *argv[])
1011 {
1012         char *dup, *cur;
1013         int x=0;
1014         int quoted=0;
1015         int escaped=0;
1016         int whitespace=1;
1017
1018         dup = strdup(s);
1019         if (dup) {
1020                 cur = dup;
1021                 while(*s) {
1022                         switch(*s) {
1023                         case '"':
1024                                 /* If it's escaped, put a literal quote */
1025                                 if (escaped) 
1026                                         goto normal;
1027                                 else 
1028                                         quoted = !quoted;
1029                                 if (quoted && whitespace) {
1030                                         /* If we're starting a quote, coming off white space start a new word, too */
1031                                         argv[x++] = cur;
1032                                         whitespace=0;
1033                                 }
1034                                 escaped = 0;
1035                                 break;
1036                         case ' ':
1037                         case '\t':
1038                                 if (!quoted && !escaped) {
1039                                         /* If we're not quoted, mark this as whitespace, and
1040                                            end the previous argument */
1041                                         whitespace = 1;
1042                                         *(cur++) = '\0';
1043                                 } else
1044                                         /* Otherwise, just treat it as anything else */ 
1045                                         goto normal;
1046                                 break;
1047                         case '\\':
1048                                 /* If we're escaped, print a literal, otherwise enable escaping */
1049                                 if (escaped) {
1050                                         goto normal;
1051                                 } else {
1052                                         escaped=1;
1053                                 }
1054                                 break;
1055                         default:
1056 normal:
1057                                 if (whitespace) {
1058                                         if (x >= AST_MAX_ARGS -1) {
1059                                                 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1060                                                 break;
1061                                         }
1062                                         /* Coming off of whitespace, start the next argument */
1063                                         argv[x++] = cur;
1064                                         whitespace=0;
1065                                 }
1066                                 *(cur++) = *s;
1067                                 escaped=0;
1068                         }
1069                         s++;
1070                 }
1071                 /* Null terminate */
1072                 *(cur++) = '\0';
1073                 argv[x] = NULL;
1074                 *max = x;
1075         }
1076         return dup;
1077 }
1078
1079 /* This returns the number of unique matches for the generator */
1080 int ast_cli_generatornummatches(char *text, char *word)
1081 {
1082         int matches = 0, i = 0;
1083         char *buf = NULL, *oldbuf = NULL;
1084
1085         while ( (buf = ast_cli_generator(text, word, i)) ) {
1086                 if (++i > 1 && strcmp(buf,oldbuf) == 0)  {
1087                                 continue;
1088                 }
1089                 oldbuf = buf;
1090                 matches++;
1091         }
1092
1093         return matches;
1094 }
1095
1096 char **ast_cli_completion_matches(char *text, char *word)
1097 {
1098         char **match_list = NULL, *retstr, *prevstr;
1099         size_t match_list_len, max_equal, which, i;
1100         int matches = 0;
1101
1102         match_list_len = 1;
1103         while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1104                 if (matches + 1 >= match_list_len) {
1105                         match_list_len <<= 1;
1106                         match_list = realloc(match_list, match_list_len * sizeof(char *));
1107                 }
1108                 match_list[++matches] = retstr;
1109         }
1110
1111         if (!match_list)
1112                 return (char **) NULL;
1113
1114         which = 2;
1115         prevstr = match_list[1];
1116         max_equal = strlen(prevstr);
1117         for (; which <= matches; which++) {
1118                 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1119                         continue;
1120                 max_equal = i;
1121         }
1122
1123         retstr = malloc(max_equal + 1);
1124         (void) strncpy(retstr, match_list[1], max_equal);
1125         retstr[max_equal] = '\0';
1126         match_list[0] = retstr;
1127
1128         if (matches + 1 >= match_list_len)
1129                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1130         match_list[matches + 1] = (char *) NULL;
1131
1132         return (match_list);
1133 }
1134
1135 static char *__ast_cli_generator(char *text, char *word, int state, int lock)
1136 {
1137         char *argv[AST_MAX_ARGS];
1138         struct ast_cli_entry *e, *e1, *e2;
1139         int x;
1140         int matchnum=0;
1141         char *dup, *res;
1142         char fullcmd1[80] = "";
1143         char fullcmd2[80] = "";
1144         char matchstr[80];
1145         char *fullcmd = NULL;
1146
1147         if ((dup = parse_args(text, &x, argv))) {
1148                 join(matchstr, sizeof(matchstr), argv);
1149                 if (lock)
1150                         ast_mutex_lock(&clilock);
1151                 e1 = builtins;
1152                 e2 = helpers;
1153                 while(e1->cmda[0] || e2) {
1154                         if (e2)
1155                                 join(fullcmd2, sizeof(fullcmd2), e2->cmda);
1156                         if (e1->cmda[0])
1157                                 join(fullcmd1, sizeof(fullcmd1), e1->cmda);
1158                         if (!e1->cmda[0] || 
1159                                         (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
1160                                 /* Use e2 */
1161                                 e = e2;
1162                                 fullcmd = fullcmd2;
1163                                 /* Increment by going to next */
1164                                 e2 = e2->next;
1165                         } else {
1166                                 /* Use e1 */
1167                                 e = e1;
1168                                 fullcmd = fullcmd1;
1169                                 e1++;
1170                         }
1171                         if ((fullcmd[0] != '_') && !strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1172                                 /* We contain the first part of one or more commands */
1173                                 matchnum++;
1174                                 if (matchnum > state) {
1175                                         /* Now, what we're supposed to return is the next word... */
1176                                         if (!ast_strlen_zero(word) && x>0) {
1177                                                 res = e->cmda[x-1];
1178                                         } else {
1179                                                 res = e->cmda[x];
1180                                         }
1181                                         if (res) {
1182                                                 if (lock)
1183                                                         ast_mutex_unlock(&clilock);
1184                                                 free(dup);
1185                                                 return res ? strdup(res) : NULL;
1186                                         }
1187                                 }
1188                         }
1189                         if (e->generator && !strncasecmp(matchstr, fullcmd, strlen(fullcmd))) {
1190                                 /* We have a command in its entirity within us -- theoretically only one
1191                                    command can have this occur */
1192                                 fullcmd = e->generator(matchstr, word, (!ast_strlen_zero(word) ? (x - 1) : (x)), state);
1193                                 if (lock)
1194                                         ast_mutex_unlock(&clilock);
1195                                 free(dup);
1196                                 return fullcmd;
1197                         }
1198                         
1199                 }
1200                 if (lock)
1201                         ast_mutex_unlock(&clilock);
1202                 free(dup);
1203         }
1204         return NULL;
1205 }
1206
1207 char *ast_cli_generator(char *text, char *word, int state)
1208 {
1209         return __ast_cli_generator(text, word, state, 1);
1210 }
1211
1212 int ast_cli_command(int fd, char *s)
1213 {
1214         char *argv[AST_MAX_ARGS];
1215         struct ast_cli_entry *e;
1216         int x;
1217         char *dup;
1218         x = AST_MAX_ARGS;
1219         if ((dup = parse_args(s, &x, argv))) {
1220                 /* We need at least one entry, or ignore */
1221                 if (x > 0) {
1222                         ast_mutex_lock(&clilock);
1223                         e = find_cli(argv, 0);
1224                         if (e)
1225                                 e->inuse++;
1226                         ast_mutex_unlock(&clilock);
1227                         if (e) {
1228                                 switch(e->handler(fd, x, argv)) {
1229                                 case RESULT_SHOWUSAGE:
1230                                         ast_cli(fd, e->usage);
1231                                         break;
1232                                 }
1233                         } else 
1234                                 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1235                         if (e) {
1236                                 ast_mutex_lock(&clilock);
1237                                 e->inuse--;
1238                                 ast_mutex_unlock(&clilock);
1239                         }
1240                 }
1241                 free(dup);
1242         } else {
1243                 ast_log(LOG_WARNING, "Out of memory\n");        
1244                 return -1;
1245         }
1246         return 0;
1247 }