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