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