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