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