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