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