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