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