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