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