Fix chan_phone error code (bug #3692)
[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 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 nodebugchan_help[] = 
446 "Usage: no debug channel <channel>\n"
447 "       Disables debugging on a specific channel.\n";
448
449 static char commandcomplete_help[] = 
450 "Usage: _command complete \"<line>\" text state\n"
451 "       This function is used internally to help with command completion and should.\n"
452 "       never be called by the user directly.\n";
453
454 static char commandnummatches_help[] = 
455 "Usage: _command nummatches \"<line>\" text \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 commandmatchesarray_help[] = 
460 "Usage: _command matchesarray \"<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 int handle_softhangup(int fd, int argc, char *argv[])
465 {
466         struct ast_channel *c=NULL;
467         if (argc != 3)
468                 return RESULT_SHOWUSAGE;
469         c = ast_channel_walk_locked(NULL);
470         while(c) {
471                 if (!strcasecmp(c->name, argv[2])) {
472                         ast_cli(fd, "Requested Hangup on channel '%s'\n", c->name);
473                         ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
474                         ast_mutex_unlock(&c->lock);
475                         break;
476                 }
477                 ast_mutex_unlock(&c->lock);
478                 c = ast_channel_walk_locked(c);
479         }
480         if (!c) 
481                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
482         return RESULT_SUCCESS;
483 }
484
485 static char *__ast_cli_generator(char *text, char *word, int state, int lock);
486
487 static int handle_commandmatchesarray(int fd, int argc, char *argv[])
488 {
489         char *buf, *obuf;
490         int buflen = 2048;
491         int len = 0;
492         char **matches;
493         int x, matchlen;
494
495         if (argc != 4)
496                 return RESULT_SHOWUSAGE;
497         buf = malloc(buflen);
498         if (!buf)
499                 return RESULT_FAILURE;
500         buf[len] = '\0';
501         matches = ast_cli_completion_matches(argv[2], argv[3]);
502         if (matches) {
503                 for (x=0; matches[x]; x++) {
504 #if 0
505                         printf("command matchesarray for '%s' %s got '%s'\n", argv[2], argv[3], matches[x]);
506 #endif
507                         matchlen = strlen(matches[x]) + 1;
508                         if (len + matchlen >= buflen) {
509                                 buflen += matchlen * 3;
510                                 obuf = buf;
511                                 buf = realloc(obuf, buflen);
512                                 if (!buf) 
513                                         /* Out of memory...  Just free old buffer and be done */
514                                         free(obuf);
515                         }
516                         if (buf)
517                                 len += sprintf( buf + len, "%s ", matches[x]);
518                         free(matches[x]);
519                         matches[x] = NULL;
520                 }
521                 free(matches);
522         }
523 #if 0
524         printf("array for '%s' %s got '%s'\n", argv[2], argv[3], buf);
525 #endif
526         
527         if (buf) {
528                 ast_cli(fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
529                 free(buf);
530         } else
531                 ast_cli(fd, "NULL\n");
532
533         return RESULT_SUCCESS;
534 }
535
536
537
538 static int handle_commandnummatches(int fd, int argc, char *argv[])
539 {
540         int matches = 0;
541
542         if (argc != 4)
543                 return RESULT_SHOWUSAGE;
544
545         matches = ast_cli_generatornummatches(argv[2], argv[3]);
546
547 #if 0
548         printf("Search for '%s' %s got '%d'\n", argv[2], argv[3], matches);
549 #endif
550         ast_cli(fd, "%d", matches);
551
552         return RESULT_SUCCESS;
553 }
554
555 static int handle_commandcomplete(int fd, int argc, char *argv[])
556 {
557         char *buf;
558 #if 0
559         printf("Search for %d args: '%s', '%s', '%s', '%s'\n", argc, argv[0], argv[1], argv[2], argv[3]);
560 #endif  
561         if (argc != 5)
562                 return RESULT_SHOWUSAGE;
563         buf = __ast_cli_generator(argv[2], argv[3], atoi(argv[4]), 0);
564 #if 0
565         printf("Search for '%s' %s %d got '%s'\n", argv[2], argv[3], atoi(argv[4]), buf);
566 #endif  
567         if (buf) {
568                 ast_cli(fd, buf);
569                 free(buf);
570         } else
571                 ast_cli(fd, "NULL\n");
572         return RESULT_SUCCESS;
573 }
574
575 static int handle_debugchan(int fd, int argc, char *argv[])
576 {
577         struct ast_channel *c=NULL;
578         int is_all;
579         if (argc != 3)
580                 return RESULT_SHOWUSAGE;
581
582         is_all = !strcasecmp("all", argv[2]);
583         if (is_all) {
584                 global_fin |= 0x80000000;
585                 global_fout |= 0x80000000;
586         }
587         c = ast_channel_walk_locked(NULL);
588         while(c) {
589                 if (is_all || !strcasecmp(c->name, argv[2])) {
590                         if (!(c->fin & 0x80000000) || !(c->fout & 0x80000000)) {
591                                 c->fin |= 0x80000000;
592                                 c->fout |= 0x80000000;
593                                 ast_cli(fd, "Debugging enabled on channel %s\n", c->name);
594                         }
595                         if (!is_all)
596                                 break;
597                 }
598                 ast_mutex_unlock(&c->lock);
599                 c = ast_channel_walk_locked(c);
600         }
601         if (!is_all) {
602                 if (c)
603                         ast_mutex_unlock(&c->lock);
604                 else
605                         ast_cli(fd, "No such channel %s\n", argv[2]);
606         }
607         else
608                 ast_cli(fd, "Debugging on new channels is enabled\n");
609         return RESULT_SUCCESS;
610 }
611
612 static int handle_nodebugchan(int fd, int argc, char *argv[])
613 {
614         struct ast_channel *c=NULL;
615         int is_all;
616         if (argc != 4)
617                 return RESULT_SHOWUSAGE;
618         is_all = !strcasecmp("all", argv[3]);
619         if (is_all) {
620                 global_fin &= ~0x80000000;
621                 global_fout &= ~0x80000000;
622         }
623         c = ast_channel_walk_locked(NULL);
624         while(c) {
625                 if (is_all || !strcasecmp(c->name, argv[3])) {
626                         if ((c->fin & 0x80000000) || (c->fout & 0x80000000)) {
627                                 c->fin &= 0x7fffffff;
628                                 c->fout &= 0x7fffffff;
629                                 ast_cli(fd, "Debugging disabled on channel %s\n", c->name);
630                         }
631                         if (!is_all)
632                                 break;
633                 }
634                 ast_mutex_unlock(&c->lock);
635                 c = ast_channel_walk_locked(c);
636         }
637         if (!is_all) {
638                 if (c)
639                         ast_mutex_unlock(&c->lock);
640                 else
641                         ast_cli(fd, "No such channel %s\n", argv[3]);
642         }
643         else
644                 ast_cli(fd, "Debugging on new channels is disabled\n");
645         return RESULT_SUCCESS;
646 }
647                 
648         
649
650 static int handle_showchan(int fd, int argc, char *argv[])
651 {
652         struct ast_channel *c=NULL;
653         struct timeval now;
654         char buf[2048];
655         char cdrtime[256];
656         long elapsed_seconds=0;
657         int hour=0, min=0, sec=0;
658         
659         if (argc != 3)
660                 return RESULT_SHOWUSAGE;
661         gettimeofday(&now, NULL);
662         c = ast_channel_walk_locked(NULL);
663         while(c) {
664                 if (!strcasecmp(c->name, argv[2])) {
665                         if(c->cdr) {
666                                 elapsed_seconds = now.tv_sec - c->cdr->start.tv_sec;
667                                 hour = elapsed_seconds / 3600;
668                                 min = (elapsed_seconds % 3600) / 60;
669                                 sec = elapsed_seconds % 60;
670                                 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
671                         } else
672                                 strncpy(cdrtime, "N/A", sizeof(cdrtime) -1);
673                         ast_cli(fd, 
674         " -- General --\n"
675         "           Name: %s\n"
676         "           Type: %s\n"
677         "       UniqueID: %s\n"
678         "      Caller ID: %s\n"
679         " Caller ID Name: %s\n"
680         "    DNID Digits: %s\n"
681         "          State: %s (%d)\n"
682         "          Rings: %d\n"
683         "   NativeFormat: %d\n"
684         "    WriteFormat: %d\n"
685         "     ReadFormat: %d\n"
686         "1st File Descriptor: %d\n"
687         "      Frames in: %d%s\n"
688         "     Frames out: %d%s\n"
689         " Time to Hangup: %ld\n"
690         "   Elapsed Time: %s\n"
691         "  Direct Bridge: %s\n"
692         "Indirect Bridge: %s\n"
693         " --   PBX   --\n"
694         "        Context: %s\n"
695         "      Extension: %s\n"
696         "       Priority: %d\n"
697         "     Call Group: %d\n"
698         "   Pickup Group: %d\n"
699         "    Application: %s\n"
700         "           Data: %s\n"
701         "    Blocking in: %s\n",
702         c->name, c->type, c->uniqueid,
703         (c->cid.cid_num ? c->cid.cid_num : "(N/A)"),
704         (c->cid.cid_name ? c->cid.cid_name : "(N/A)"),
705         (c->cid.cid_dnid ? c->cid.cid_dnid : "(N/A)" ), ast_state2str(c->_state), c->_state, c->rings, c->nativeformats, c->writeformat, c->readformat,
706         c->fds[0], c->fin & 0x7fffffff, (c->fin & 0x80000000) ? " (DEBUGGED)" : "",
707         c->fout & 0x7fffffff, (c->fout & 0x80000000) ? " (DEBUGGED)" : "", (long)c->whentohangup,
708         cdrtime, c->_bridge ? c->_bridge->name : "<none>", ast_bridged_channel(c) ? ast_bridged_channel(c)->name : "<none>", 
709         c->context, c->exten, c->priority, c->callgroup, c->pickupgroup, ( c->appl ? c->appl : "(N/A)" ),
710         ( c-> data ? (!ast_strlen_zero(c->data) ? c->data : "(Empty)") : "(None)"),
711         (ast_test_flag(c, AST_FLAG_BLOCKING) ? c->blockproc : "(Not Blocking)"));
712                         if(pbx_builtin_serialize_variables(c,buf,sizeof(buf)))
713                                 ast_cli(fd,"      Variables:\n%s\n",buf);
714                         if(c->cdr && ast_cdr_serialize_variables(c->cdr,buf, sizeof(buf), '=', '\n', 1))
715                                 ast_cli(fd,"  CDR Variables:\n%s\n",buf);
716
717                         ast_mutex_unlock(&c->lock);
718                 break;
719                 }
720                 ast_mutex_unlock(&c->lock);
721                 c = ast_channel_walk_locked(c);
722         }
723         if (!c) 
724                 ast_cli(fd, "%s is not a known channel\n", argv[2]);
725         return RESULT_SUCCESS;
726 }
727
728 static char *complete_ch_helper(char *line, char *word, int pos, int state, int rpos)
729 {
730         struct ast_channel *c;
731         int which=0;
732         char *ret;
733         if (pos != rpos)
734                 return NULL;
735         c = ast_channel_walk_locked(NULL);
736         while(c) {
737                 if (!strncasecmp(word, c->name, strlen(word))) {
738                         if (++which > state)
739                                 break;
740                 }
741                 ast_mutex_unlock(&c->lock);
742                 c = ast_channel_walk_locked(c);
743         }
744         if (c) {
745                 ret = strdup(c->name);
746                 ast_mutex_unlock(&c->lock);
747         } else
748                 ret = NULL;
749         return ret;
750 }
751
752 static char *complete_ch_3(char *line, char *word, int pos, int state)
753 {
754         return complete_ch_helper(line, word, pos, state, 2);
755 }
756
757 static char *complete_ch_4(char *line, char *word, int pos, int state)
758 {
759         return complete_ch_helper(line, word, pos, state, 3);
760 }
761
762 static char *complete_mod_2(char *line, char *word, int pos, int state)
763 {
764         return ast_module_helper(line, word, pos, state, 1, 1);
765 }
766
767 static char *complete_mod_4(char *line, char *word, int pos, int state)
768 {
769         return ast_module_helper(line, word, pos, state, 3, 0);
770 }
771
772 static char *complete_fn(char *line, char *word, int pos, int state)
773 {
774         char *c;
775         char filename[256];
776         if (pos != 1)
777                 return NULL;
778         if (word[0] == '/')
779                 strncpy(filename, word, sizeof(filename)-1);
780         else
781                 snprintf(filename, sizeof(filename), "%s/%s", (char *)ast_config_AST_MODULE_DIR, word);
782         c = (char*)filename_completion_function(filename, state);
783         if (c && word[0] != '/')
784                 c += (strlen((char*)ast_config_AST_MODULE_DIR) + 1);
785         return c ? strdup(c) : c;
786 }
787
788 static int handle_help(int fd, int argc, char *argv[]);
789
790 static struct ast_cli_entry builtins[] = {
791         /* Keep alphabetized, with longer matches first (example: abcd before abc) */
792         { { "_command", "complete", NULL }, handle_commandcomplete, "Command complete", commandcomplete_help },
793         { { "_command", "nummatches", NULL }, handle_commandnummatches, "Returns number of command matches", commandnummatches_help },
794         { { "_command", "matchesarray", NULL }, handle_commandmatchesarray, "Returns command matches array", commandmatchesarray_help },
795         { { "debug", "channel", NULL }, handle_debugchan, "Enable debugging on a channel", debugchan_help, complete_ch_3 },
796         { { "help", NULL }, handle_help, "Display help list, or specific help on a command", help_help },
797         { { "load", NULL }, handle_load, "Load a dynamic module by name", load_help, complete_fn },
798         { { "no", "debug", "channel", NULL }, handle_nodebugchan, "Disable debugging on a channel", nodebugchan_help, complete_ch_4 },
799         { { "reload", NULL }, handle_reload, "Reload configuration", reload_help, complete_mod_2 },
800         { { "set", "debug", NULL }, handle_set_debug, "Set level of debug chattiness", set_debug_help },
801         { { "set", "verbose", NULL }, handle_set_verbose, "Set level of verboseness", set_verbose_help },
802         { { "show", "channel", NULL }, handle_showchan, "Display information on a specific channel", showchan_help, complete_ch_3 },
803         { { "show", "channels", NULL }, handle_chanlist, "Display information on channels", chanlist_help },
804         { { "show", "modules", NULL }, handle_modlist, "List modules and info", modlist_help },
805         { { "show", "modules", "like", NULL }, handle_modlist, "List modules and info", modlist_help, complete_mod_4 },
806         { { "show", "uptime", NULL }, handle_showuptime, "Show uptime information", uptime_help },
807         { { "show", "version", NULL }, handle_version, "Display version info", version_help },
808         { { "soft", "hangup", NULL }, handle_softhangup, "Request a hangup on a given channel", softhangup_help, complete_ch_3 },
809         { { "unload", NULL }, handle_unload, "Unload a dynamic module by name", unload_help, complete_fn },
810         { { NULL }, NULL, NULL, NULL }
811 };
812
813 static struct ast_cli_entry *find_cli(char *cmds[], int exact)
814 {
815         int x;
816         int y;
817         int match;
818         struct ast_cli_entry *e=NULL;
819         for (x=0;builtins[x].cmda[0];x++) {
820                 /* start optimistic */
821                 match = 1;
822                 for (y=0;match && cmds[y]; y++) {
823                         /* If there are no more words in the candidate command, then we're
824                            there.  */
825                         if (!builtins[x].cmda[y] && !exact)
826                                 break;
827                         /* If there are no more words in the command (and we're looking for
828                            an exact match) or there is a difference between the two words,
829                            then this is not a match */
830                         if (!builtins[x].cmda[y] || strcasecmp(builtins[x].cmda[y], cmds[y]))
831                                 match = 0;
832                 }
833                 /* If more words are needed to complete the command then this is not
834                    a candidate (unless we're looking for a really inexact answer  */
835                 if ((exact > -1) && builtins[x].cmda[y])
836                         match = 0;
837                 if (match)
838                         return &builtins[x];
839         }
840         for (e=helpers;e;e=e->next) {
841                 match = 1;
842                 for (y=0;match && cmds[y]; y++) {
843                         if (!e->cmda[y] && !exact)
844                                 break;
845                         if (!e->cmda[y] || strcasecmp(e->cmda[y], cmds[y]))
846                                 match = 0;
847                 }
848                 if ((exact > -1) && e->cmda[y])
849                         match = 0;
850                 if (match)
851                         break;
852         }
853         return e;
854 }
855
856 static void join(char *dest, size_t destsize, char *w[])
857 {
858         int x;
859         /* Join words into a string */
860         if (!dest || destsize < 1) {
861                 return;
862         }
863         dest[0] = '\0';
864         for (x=0;w[x];x++) {
865                 if (x)
866                         strncat(dest, " ", destsize - strlen(dest) - 1);
867                 strncat(dest, w[x], destsize - strlen(dest) - 1);
868         }
869 }
870
871 static void join2(char *dest, size_t destsize, char *w[])
872 {
873         int x;
874         /* Join words into a string */
875         if (!dest || destsize < 1) {
876                 return;
877         }
878         dest[0] = '\0';
879         for (x=0;w[x];x++) {
880                 strncat(dest, w[x], destsize - strlen(dest) - 1);
881         }
882 }
883
884 static char *find_best(char *argv[])
885 {
886         static char cmdline[80];
887         int x;
888         /* See how close we get, then print the  */
889         char *myargv[AST_MAX_CMD_LEN];
890         for (x=0;x<AST_MAX_CMD_LEN;x++)
891                 myargv[x]=NULL;
892         for (x=0;argv[x];x++) {
893                 myargv[x] = argv[x];
894                 if (!find_cli(myargv, -1))
895                         break;
896         }
897         join(cmdline, sizeof(cmdline), myargv);
898         return cmdline;
899 }
900
901 int ast_cli_unregister(struct ast_cli_entry *e)
902 {
903         struct ast_cli_entry *cur, *l=NULL;
904         ast_mutex_lock(&clilock);
905         cur = helpers;
906         while(cur) {
907                 if (e == cur) {
908                         if (e->inuse) {
909                                 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
910                         } else {
911                                 /* Rewrite */
912                                 if (l)
913                                         l->next = e->next;
914                                 else
915                                         helpers = e->next;
916                                 e->next = NULL;
917                                 break;
918                         }
919                 }
920                 l = cur;
921                 cur = cur->next;
922         }
923         ast_mutex_unlock(&clilock);
924         return 0;
925 }
926
927 int ast_cli_register(struct ast_cli_entry *e)
928 {
929         struct ast_cli_entry *cur, *l=NULL;
930         char fulle[80] ="", fulltst[80] ="";
931         static int len;
932         ast_mutex_lock(&clilock);
933         join2(fulle, sizeof(fulle), e->cmda);
934         if (find_cli(e->cmda, -1)) {
935                 ast_mutex_unlock(&clilock);
936                 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n", fulle);
937                 return -1;
938         }
939         cur = helpers;
940         while(cur) {
941                 join2(fulltst, sizeof(fulltst), cur->cmda);
942                 len = strlen(fulltst);
943                 if (strlen(fulle) < len)
944                         len = strlen(fulle);
945                 if (strncasecmp(fulle, fulltst, len) < 0) {
946                         if (l) {
947                                 e->next = l->next;
948                                 l->next = e;
949                         } else {
950                                 e->next = helpers;
951                                 helpers = e;
952                         }
953                         break;
954                 }
955                 l = cur;
956                 cur = cur->next;
957         }
958         if (!cur) {
959                 if (l)
960                         l->next = e;
961                 else
962                         helpers = e;
963                 e->next = NULL;
964         }
965         ast_mutex_unlock(&clilock);
966         return 0;
967 }
968
969 static int help_workhorse(int fd, char *match[])
970 {
971         char fullcmd1[80] = "";
972         char fullcmd2[80] = "";
973         char matchstr[80];
974         char *fullcmd = NULL;
975         struct ast_cli_entry *e, *e1, *e2;
976         e1 = builtins;
977         e2 = helpers;
978         if (match)
979                 join(matchstr, sizeof(matchstr), match);
980         while(e1->cmda[0] || e2) {
981                 if (e2)
982                         join(fullcmd2, sizeof(fullcmd2), e2->cmda);
983                 if (e1->cmda[0])
984                         join(fullcmd1, sizeof(fullcmd1), e1->cmda);
985                 if (!e1->cmda[0] || 
986                                 (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
987                         /* Use e2 */
988                         e = e2;
989                         fullcmd = fullcmd2;
990                         /* Increment by going to next */
991                         e2 = e2->next;
992                 } else {
993                         /* Use e1 */
994                         e = e1;
995                         fullcmd = fullcmd1;
996                         e1++;
997                 }
998                 /* Hide commands that start with '_' */
999                 if (fullcmd[0] == '_')
1000                         continue;
1001                 if (match) {
1002                         if (strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1003                                 continue;
1004                         }
1005                 }
1006                 ast_cli(fd, "%25.25s  %s\n", fullcmd, e->summary);
1007         }
1008         return 0;
1009 }
1010
1011 static int handle_help(int fd, int argc, char *argv[]) {
1012         struct ast_cli_entry *e;
1013         char fullcmd[80];
1014         if ((argc < 1))
1015                 return RESULT_SHOWUSAGE;
1016         if (argc > 1) {
1017                 e = find_cli(argv + 1, 1);
1018                 if (e) 
1019                         ast_cli(fd, e->usage);
1020                 else {
1021                         if (find_cli(argv + 1, -1)) {
1022                                 return help_workhorse(fd, argv + 1);
1023                         } else {
1024                                 join(fullcmd, sizeof(fullcmd), argv+1);
1025                                 ast_cli(fd, "No such command '%s'.\n", fullcmd);
1026                         }
1027                 }
1028         } else {
1029                 return help_workhorse(fd, NULL);
1030         }
1031         return RESULT_SUCCESS;
1032 }
1033
1034 static char *parse_args(char *s, int *max, char *argv[])
1035 {
1036         char *dup, *cur;
1037         int x=0;
1038         int quoted=0;
1039         int escaped=0;
1040         int whitespace=1;
1041
1042         dup = strdup(s);
1043         if (dup) {
1044                 cur = dup;
1045                 while(*s) {
1046                         switch(*s) {
1047                         case '"':
1048                                 /* If it's escaped, put a literal quote */
1049                                 if (escaped) 
1050                                         goto normal;
1051                                 else 
1052                                         quoted = !quoted;
1053                                 if (quoted && whitespace) {
1054                                         /* If we're starting a quote, coming off white space start a new word, too */
1055                                         argv[x++] = cur;
1056                                         whitespace=0;
1057                                 }
1058                                 escaped = 0;
1059                                 break;
1060                         case ' ':
1061                         case '\t':
1062                                 if (!quoted && !escaped) {
1063                                         /* If we're not quoted, mark this as whitespace, and
1064                                            end the previous argument */
1065                                         whitespace = 1;
1066                                         *(cur++) = '\0';
1067                                 } else
1068                                         /* Otherwise, just treat it as anything else */ 
1069                                         goto normal;
1070                                 break;
1071                         case '\\':
1072                                 /* If we're escaped, print a literal, otherwise enable escaping */
1073                                 if (escaped) {
1074                                         goto normal;
1075                                 } else {
1076                                         escaped=1;
1077                                 }
1078                                 break;
1079                         default:
1080 normal:
1081                                 if (whitespace) {
1082                                         if (x >= AST_MAX_ARGS -1) {
1083                                                 ast_log(LOG_WARNING, "Too many arguments, truncating\n");
1084                                                 break;
1085                                         }
1086                                         /* Coming off of whitespace, start the next argument */
1087                                         argv[x++] = cur;
1088                                         whitespace=0;
1089                                 }
1090                                 *(cur++) = *s;
1091                                 escaped=0;
1092                         }
1093                         s++;
1094                 }
1095                 /* Null terminate */
1096                 *(cur++) = '\0';
1097                 argv[x] = NULL;
1098                 *max = x;
1099         }
1100         return dup;
1101 }
1102
1103 /* This returns the number of unique matches for the generator */
1104 int ast_cli_generatornummatches(char *text, char *word)
1105 {
1106         int matches = 0, i = 0;
1107         char *buf = NULL, *oldbuf = NULL;
1108
1109         while ( (buf = ast_cli_generator(text, word, i)) ) {
1110                 if (++i > 1 && strcmp(buf,oldbuf) == 0)  {
1111                                 continue;
1112                 }
1113                 oldbuf = buf;
1114                 matches++;
1115         }
1116
1117         return matches;
1118 }
1119
1120 char **ast_cli_completion_matches(char *text, char *word)
1121 {
1122         char **match_list = NULL, *retstr, *prevstr;
1123         size_t match_list_len, max_equal, which, i;
1124         int matches = 0;
1125
1126         match_list_len = 1;
1127         while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
1128                 if (matches + 1 >= match_list_len) {
1129                         match_list_len <<= 1;
1130                         match_list = realloc(match_list, match_list_len * sizeof(char *));
1131                 }
1132                 match_list[++matches] = retstr;
1133         }
1134
1135         if (!match_list)
1136                 return (char **) NULL;
1137
1138         which = 2;
1139         prevstr = match_list[1];
1140         max_equal = strlen(prevstr);
1141         for (; which <= matches; which++) {
1142                 for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
1143                         continue;
1144                 max_equal = i;
1145         }
1146
1147         retstr = malloc(max_equal + 1);
1148         (void) strncpy(retstr, match_list[1], max_equal);
1149         retstr[max_equal] = '\0';
1150         match_list[0] = retstr;
1151
1152         if (matches + 1 >= match_list_len)
1153                 match_list = realloc(match_list, (match_list_len + 1) * sizeof(char *));
1154         match_list[matches + 1] = (char *) NULL;
1155
1156         return (match_list);
1157 }
1158
1159 static char *__ast_cli_generator(char *text, char *word, int state, int lock)
1160 {
1161         char *argv[AST_MAX_ARGS];
1162         struct ast_cli_entry *e, *e1, *e2;
1163         int x;
1164         int matchnum=0;
1165         char *dup, *res;
1166         char fullcmd1[80] = "";
1167         char fullcmd2[80] = "";
1168         char matchstr[80];
1169         char *fullcmd = NULL;
1170
1171         if ((dup = parse_args(text, &x, argv))) {
1172                 join(matchstr, sizeof(matchstr), argv);
1173                 if (lock)
1174                         ast_mutex_lock(&clilock);
1175                 e1 = builtins;
1176                 e2 = helpers;
1177                 while(e1->cmda[0] || e2) {
1178                         if (e2)
1179                                 join(fullcmd2, sizeof(fullcmd2), e2->cmda);
1180                         if (e1->cmda[0])
1181                                 join(fullcmd1, sizeof(fullcmd1), e1->cmda);
1182                         if (!e1->cmda[0] || 
1183                                         (e2 && (strcmp(fullcmd2, fullcmd1) < 0))) {
1184                                 /* Use e2 */
1185                                 e = e2;
1186                                 fullcmd = fullcmd2;
1187                                 /* Increment by going to next */
1188                                 e2 = e2->next;
1189                         } else {
1190                                 /* Use e1 */
1191                                 e = e1;
1192                                 fullcmd = fullcmd1;
1193                                 e1++;
1194                         }
1195                         if ((fullcmd[0] != '_') && !strncasecmp(matchstr, fullcmd, strlen(matchstr))) {
1196                                 /* We contain the first part of one or more commands */
1197                                 /* Now, what we're supposed to return is the next word... */
1198                                 if (!ast_strlen_zero(word) && x>0) {
1199                                         res = e->cmda[x-1];
1200                                 } else {
1201                                         res = e->cmda[x];
1202                                 }
1203                                 if (res) {
1204                                         matchnum++;
1205                                         if (matchnum > state) {
1206                                                 if (lock)
1207                                                         ast_mutex_unlock(&clilock);
1208                                                 free(dup);
1209                                                 return strdup(res);
1210                                         }
1211                                 }
1212                         }
1213                         if (e->generator && !strncasecmp(matchstr, fullcmd, strlen(fullcmd))) {
1214                                 /* We have a command in its entirity within us -- theoretically only one
1215                                    command can have this occur */
1216                                 fullcmd = e->generator(matchstr, word, (!ast_strlen_zero(word) ? (x - 1) : (x)), state);
1217                                 if (fullcmd) {
1218                                         if (lock)
1219                                                 ast_mutex_unlock(&clilock);
1220                                         free(dup);
1221                                         return fullcmd;
1222                                 }
1223                         }
1224                         
1225                 }
1226                 if (lock)
1227                         ast_mutex_unlock(&clilock);
1228                 free(dup);
1229         }
1230         return NULL;
1231 }
1232
1233 char *ast_cli_generator(char *text, char *word, int state)
1234 {
1235         return __ast_cli_generator(text, word, state, 1);
1236 }
1237
1238 int ast_cli_command(int fd, char *s)
1239 {
1240         char *argv[AST_MAX_ARGS];
1241         struct ast_cli_entry *e;
1242         int x;
1243         char *dup;
1244         x = AST_MAX_ARGS;
1245         if ((dup = parse_args(s, &x, argv))) {
1246                 /* We need at least one entry, or ignore */
1247                 if (x > 0) {
1248                         ast_mutex_lock(&clilock);
1249                         e = find_cli(argv, 0);
1250                         if (e)
1251                                 e->inuse++;
1252                         ast_mutex_unlock(&clilock);
1253                         if (e) {
1254                                 switch(e->handler(fd, x, argv)) {
1255                                 case RESULT_SHOWUSAGE:
1256                                         ast_cli(fd, e->usage);
1257                                         break;
1258                                 }
1259                         } else 
1260                                 ast_cli(fd, "No such command '%s' (type 'help' for help)\n", find_best(argv));
1261                         if (e) {
1262                                 ast_mutex_lock(&clilock);
1263                                 e->inuse--;
1264                                 ast_mutex_unlock(&clilock);
1265                         }
1266                 }
1267                 free(dup);
1268         } else {
1269                 ast_log(LOG_WARNING, "Out of memory\n");        
1270                 return -1;
1271         }
1272         return 0;
1273 }