Debian Codegraph @

main/cli.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2006, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
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 * \author Mark Spencer <[email protected]>
24 */
25
26 /*! \li \ref cli.c uses the configuration file \ref cli_permissions.conf
27 * \addtogroup configuration_file Configuration Files
28 */
29
30 /*!
31 * \page cli_permissions.conf cli_permissions.conf
32 * \verbinclude cli_permissions.conf.sample
33 */
34
35 /*** MODULEINFO
36 <support_level>core</support_level>
37 ***/
38
39 #include "asterisk.h"
40
41 #include "asterisk/_private.h"
42 #include "asterisk/paths.h" /* use ast_config_AST_MODULE_DIR */
43 #include <signal.h>
44 #include <ctype.h>
45 #include <regex.h>
46 #include <pwd.h>
47 #include <grp.h>
48 #include <fnmatch.h>
49
50 #include "asterisk/cli.h"
51 #include "asterisk/linkedlists.h"
52 #include "asterisk/module.h"
53 #include "asterisk/pbx.h"
54 #include "asterisk/channel.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/app.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/threadstorage.h"
59 #include "asterisk/logger_category.h"
60 #include "asterisk/translate.h"
61 #include "asterisk/bridge.h"
62 #include "asterisk/stasis_channels.h"
63 #include "asterisk/stasis_bridges.h"
64 #include "asterisk/vector.h"
65 #include "asterisk/stream.h"
66
67 /*!
68 * \brief List of restrictions per user.
69 */
70 struct cli_perm {
71 unsigned int permit:1; /*!< 1=Permit 0=Deny */
72 char *command; /*!< Command name (to apply restrictions) */
73 AST_LIST_ENTRY(cli_perm) list;
74 };
75
76 AST_LIST_HEAD_NOLOCK(cli_perm_head, cli_perm);
77
78 /*! \brief list of users to apply restrictions. */
79 struct usergroup_cli_perm {
80 int uid; /*!< User ID (-1 disabled) */
81 int gid; /*!< Group ID (-1 disabled) */
82 struct cli_perm_head *perms; /*!< List of permissions. */
83 AST_LIST_ENTRY(usergroup_cli_perm) list;/*!< List mechanics */
84 };
85 /*! \brief CLI permissions config file. */
86 static const char perms_config[] = "cli_permissions.conf";
87 /*! \brief Default permissions value 1=Permit 0=Deny */
88 static int cli_default_perm = 1;
89
90 /*! \brief mutex used to prevent a user from running the 'cli reload permissions' command while
91 * it is already running. */
92 AST_MUTEX_DEFINE_STATIC(permsconfiglock);
93 /*! \brief List of users and permissions. */
94 static AST_RWLIST_HEAD_STATIC(cli_perms, usergroup_cli_perm);
95
96 /*!
97 * \brief map a debug or verbose level to a module name
98 */
99 struct module_level {
100 unsigned int level;
101 AST_RWLIST_ENTRY(module_level) entry;
102 char module[0];
103 };
104
105 AST_RWLIST_HEAD(module_level_list, module_level);
106
107 /*! lists of module names and their debug/trace levels */
108 static struct module_level_list debug_modules = AST_RWLIST_HEAD_INIT_VALUE;
109 static struct module_level_list trace_modules = AST_RWLIST_HEAD_INIT_VALUE;
110
111 AST_THREADSTORAGE(ast_cli_buf);
112
113 AST_RWLOCK_DEFINE_STATIC(shutdown_commands_lock);
114 static AST_VECTOR(, struct ast_cli_entry *) shutdown_commands;
115
116 /*! \brief Initial buffer size for resulting strings in ast_cli() */
117 #define AST_CLI_INITLEN 256
118
119 #define MAX_REGEX_ERROR_LEN 128
120
121 void ast_cli(int fd, const char *fmt, ...)
122 {
123 int res;
124 struct ast_str *buf;
125 va_list ap;
126
127 if (!(buf = ast_str_thread_get(&ast_cli_buf, AST_CLI_INITLEN)))
128 return;
129
130 va_start(ap, fmt);
131 res = ast_str_set_va(&buf, 0, fmt, ap);
132 va_end(ap);
133
134 if (res != AST_DYNSTR_BUILD_FAILED) {
135 ast_carefulwrite(fd, ast_str_buffer(buf), ast_str_strlen(buf), 100);
136 }
137 }
138
139 unsigned int ast_debug_get_by_module(const char *module)
140 {
141 struct module_level *ml;
142 unsigned int res = 0;
143
144 AST_RWLIST_RDLOCK(&debug_modules);
145 AST_LIST_TRAVERSE(&debug_modules, ml, entry) {
146 if (!strcasecmp(ml->module, module)) {
147 res = ml->level;
148 break;
149 }
150 }
151 AST_RWLIST_UNLOCK(&debug_modules);
152
153 return res;
154 }
155
156 unsigned int ast_trace_get_by_module(const char *module)
157 {
158 struct module_level *ml;
159 unsigned int res = 0;
160
161 AST_RWLIST_RDLOCK(&trace_modules);
162 AST_LIST_TRAVERSE(&trace_modules, ml, entry) {
163 if (!strcasecmp(ml->module, module)) {
164 res = ml->level;
165 break;
166 }
167 }
168 AST_RWLIST_UNLOCK(&trace_modules);
169
170 return res;
171 }
172
173 /*! \internal
174 * \brief Check if the user with 'uid' and 'gid' is allow to execute 'command',
175 * if command starts with '_' then not check permissions, just permit
176 * to run the 'command'.
177 * if uid == -1 or gid == -1 do not check permissions.
178 * if uid == -2 and gid == -2 is because rasterisk client didn't send
179 * the credentials, so the cli_default_perm will be applied.
180 * \param uid User ID.
181 * \param gid Group ID.
182 * \param command Command name to check permissions.
183 * \retval 1 if has permission
184 * \retval 0 if it is not allowed.
185 */
186 static int cli_has_permissions(int uid, int gid, const char *command)
187 {
188 struct usergroup_cli_perm *user_perm;
189 struct cli_perm *perm;
190 /* set to the default permissions general option. */
191 int isallowg = cli_default_perm, isallowu = -1, ispattern;
192 regex_t regexbuf;
193
194 /* if uid == -1 or gid == -1 do not check permissions.
195 if uid == -2 and gid == -2 is because rasterisk client didn't send
196 the credentials, so the cli_default_perm will be applied. */
197 if ((uid == CLI_NO_PERMS && gid == CLI_NO_PERMS) || command[0] == '_') {
198 return 1;
199 }
200
201 if (gid < 0 && uid < 0) {
202 return cli_default_perm;
203 }
204
205 AST_RWLIST_RDLOCK(&cli_perms);
206 AST_LIST_TRAVERSE(&cli_perms, user_perm, list) {
207 if (user_perm->gid != gid && user_perm->uid != uid) {
208 continue;
209 }
210 AST_LIST_TRAVERSE(user_perm->perms, perm, list) {
211 if (strcasecmp(perm->command, "all") && strncasecmp(perm->command, command, strlen(perm->command))) {
212 /* if the perm->command is a pattern, check it against command. */
213 ispattern = !regcomp(&regexbuf, perm->command, REG_EXTENDED | REG_NOSUB | REG_ICASE);
214 if (ispattern && regexec(&regexbuf, command, 0, NULL, 0)) {
215 regfree(&regexbuf);
216 continue;
217 }
218 if (!ispattern) {
219 continue;
220 }
221 regfree(&regexbuf);
222 }
223 if (user_perm->uid == uid) {
224 /* this is a user definition. */
225 isallowu = perm->permit;
226 } else {
227 /* otherwise is a group definition. */
228 isallowg = perm->permit;
229 }
230 }
231 }
232 AST_RWLIST_UNLOCK(&cli_perms);
233 if (isallowu > -1) {
234 /* user definition override group definition. */
235 isallowg = isallowu;
236 }
237
238 return isallowg;
239 }
240
241 static AST_RWLIST_HEAD_STATIC(helpers, ast_cli_entry);
242
243 static char *handle_load(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
244 {
245 /* "module load <mod>" */
246 switch (cmd) {
247 case CLI_INIT:
248 e->command = "module load";
249 e->usage =
250 "Usage: module load <module name>\n"
251 " Loads the specified module into Asterisk.\n";
252 return NULL;
253
254 case CLI_GENERATE:
255 if (a->pos != e->args) {
256 return NULL;
257 }
258 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_LOAD);
259 }
260 if (a->argc != e->args + 1) {
261 return CLI_SHOWUSAGE;
262 }
263 if (ast_load_resource(a->argv[e->args])) {
264 ast_cli(a->fd, "Unable to load module %s\n", a->argv[e->args]);
265 return CLI_FAILURE;
266 }
267 ast_cli(a->fd, "Loaded %s\n", a->argv[e->args]);
268 return CLI_SUCCESS;
269 }
270
271 static char *handle_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
272 {
273 int x;
274
275 switch (cmd) {
276 case CLI_INIT:
277 e->command = "module reload";
278 e->usage =
279 "Usage: module reload [module ...]\n"
280 " Reloads configuration files for all listed modules which support\n"
281 " reloading, or for all supported modules if none are listed.\n";
282 return NULL;
283
284 case CLI_GENERATE:
285 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_RELOAD);
286 }
287 if (a->argc == e->args) {
288 ast_module_reload(NULL);
289 return CLI_SUCCESS;
290 }
291 for (x = e->args; x < a->argc; x++) {
292 enum ast_module_reload_result res = ast_module_reload(a->argv[x]);
293 switch (res) {
294 case AST_MODULE_RELOAD_NOT_FOUND:
295 ast_cli(a->fd, "No such module '%s'\n", a->argv[x]);
296 break;
297 case AST_MODULE_RELOAD_NOT_IMPLEMENTED:
298 ast_cli(a->fd, "The module '%s' does not support reloads\n", a->argv[x]);
299 break;
300 case AST_MODULE_RELOAD_QUEUED:
301 ast_cli(a->fd, "Asterisk cannot reload a module yet; request queued\n");
302 break;
303 case AST_MODULE_RELOAD_ERROR:
304 ast_cli(a->fd, "The module '%s' reported a reload failure\n", a->argv[x]);
305 break;
306 case AST_MODULE_RELOAD_IN_PROGRESS:
307 ast_cli(a->fd, "A module reload request is already in progress; please be patient\n");
308 break;
309 case AST_MODULE_RELOAD_UNINITIALIZED:
310 ast_cli(a->fd, "The module '%s' was not properly initialized. Before reloading"
311 " the module, you must run \"module load %s\" and fix whatever is"
312 " preventing the module from being initialized.\n", a->argv[x], a->argv[x]);
313 break;
314 case AST_MODULE_RELOAD_SUCCESS:
315 ast_cli(a->fd, "Module '%s' reloaded successfully.\n", a->argv[x]);
316 break;
317 }
318 }
319 return CLI_SUCCESS;
320 }
321
322 static char *handle_core_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
323 {
324 switch (cmd) {
325 case CLI_INIT:
326 e->command = "core reload";
327 e->usage =
328 "Usage: core reload\n"
329 " Execute a global reload.\n";
330 return NULL;
331
332 case CLI_GENERATE:
333 return NULL;
334 }
335
336 if (a->argc != e->args) {
337 return CLI_SHOWUSAGE;
338 }
339
340 ast_module_reload(NULL);
341
342 return CLI_SUCCESS;
343 }
344
345 /*!
346 * \brief Find the module level setting
347 *
348 * \param module Module name to look for.
349 * \param mll List to search.
350 *
351 * \retval level struct found on success.
352 * \retval NULL not found.
353 */
354 static struct module_level *find_module_level(const char *module, struct module_level_list *mll)
355 {
356 struct module_level *ml;
357
358 AST_LIST_TRAVERSE(mll, ml, entry) {
359 if (!strcasecmp(ml->module, module))
360 return ml;
361 }
362
363 return NULL;
364 }
365
366 static char *complete_number(const char *partial, unsigned int min, unsigned int max, int n)
367 {
368 int i, count = 0;
369 unsigned int prospective[2];
370 unsigned int part = strtoul(partial, NULL, 10);
371 char next[13];
372
373 if (part < min || part > max) {
374 return NULL;
375 }
376
377 for (i = 0; i < 21; i++) {
378 if (i == 0) {
379 prospective[0] = prospective[1] = part;
380 } else if (part == 0 && !ast_strlen_zero(partial)) {
381 break;
382 } else if (i < 11) {
383 prospective[0] = prospective[1] = part * 10 + (i - 1);
384 } else {
385 prospective[0] = (part * 10 + (i - 11)) * 10;
386 prospective[1] = prospective[0] + 9;
387 }
388 if (i < 11 && (prospective[0] < min || prospective[0] > max)) {
389 continue;
390 } else if (prospective[1] < min || prospective[0] > max) {
391 continue;
392 }
393
394 if (++count > n) {
395 if (i < 11) {
396 snprintf(next, sizeof(next), "%u", prospective[0]);
397 } else {
398 snprintf(next, sizeof(next), "%u...", prospective[0] / 10);
399 }
400 return ast_strdup(next);
401 }
402 }
403 return NULL;
404 }
405
406 #define DEBUG_HANDLER 0
407 #define TRACE_HANDLER 1
408 #define VERBOSE_HANDLER 2
409
410 static void status_debug_verbose(struct ast_cli_args *a, int handler, int old_val, int cur_val)
411 {
412 char was_buf[30];
413 const char *was;
414 const char *what = "";
415
416 switch(handler) {
417 case DEBUG_HANDLER:
418 what = "Core debug";
419 break;
420 case TRACE_HANDLER:
421 what = "Core trace";
422 break;
423 case VERBOSE_HANDLER:
424 what = "Console verbose";
425 break;
426 }
427
428 if (old_val) {
429 snprintf(was_buf, sizeof(was_buf), "%d", old_val);
430 was = was_buf;
431 } else {
432 was = "OFF";
433 }
434
435 if (old_val == cur_val) {
436 ast_cli(a->fd, "%s is still %s.\n", what, was);
437 } else {
438 char now_buf[30];
439 const char *now;
440
441 if (cur_val) {
442 snprintf(now_buf, sizeof(now_buf), "%d", cur_val);
443 now = now_buf;
444 } else {
445 now = "OFF";
446 }
447
448 ast_cli(a->fd, "%s was %s and is now %s.\n", what, was, now);
449 }
450 }
451
452 static char *handle_debug_or_trace(int handler, struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
453 {
454 int oldval;
455 int newlevel;
456 int atleast = 0;
457 struct module_level *ml;
458 struct module_level_list *modules;
459 unsigned int module_option;
460 int *core_option;
461 const char *handler_name;
462
463 if (a->argc <= e->args) {
464 return CLI_SHOWUSAGE;
465 }
466
467 if (handler == DEBUG_HANDLER) {
468 modules = &debug_modules;
469 module_option = AST_OPT_FLAG_DEBUG_MODULE;
470 core_option = &option_debug;
471 handler_name = "debug";
472 } else {
473 modules = &trace_modules;
474 module_option = AST_OPT_FLAG_TRACE_MODULE;
475 core_option = &option_trace;
476 handler_name = "trace";
477 }
478
479 if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args], "off")) {
480 newlevel = 0;
481 } else {
482 if (!strcasecmp(a->argv[e->args], "atleast")) {
483 atleast = 1;
484 }
485
486 if (a->argc != e->args + atleast + 1 && a->argc != e->args + atleast + 2) {
487 return CLI_SHOWUSAGE;
488 }
489
490 if (sscanf(a->argv[e->args + atleast], "%30d", &newlevel) != 1) {
491 return CLI_SHOWUSAGE;
492 }
493
494 if (a->argc == e->args + atleast + 2) {
495 /* We have specified a module name. */
496 char *mod = ast_strdupa(a->argv[e->args + atleast + 1]);
497 int mod_len = strlen(mod);
498
499 if (3 < mod_len && !strcasecmp(mod + mod_len - 3, ".so")) {
500 mod[mod_len - 3] = '\0';
501 }
502
503 AST_RWLIST_WRLOCK(modules);
504
505 ml = find_module_level(mod, modules);
506 if (!newlevel) {
507 if (!ml) {
508 /* Specified off for a nonexistent entry. */
509 AST_RWLIST_UNLOCK(modules);
510 ast_cli(a->fd, "Core %s is still 0 for '%s'.\n", handler_name, mod);
511 return CLI_SUCCESS;
512 }
513 AST_RWLIST_REMOVE(modules, ml, entry);
514 if (AST_RWLIST_EMPTY(modules)) {
515 ast_clear_flag64(&ast_options, module_option);
516 }
517 AST_RWLIST_UNLOCK(modules);
518 ast_cli(a->fd, "Core %s was %u and has been set to 0 for '%s'.\n", handler_name,
519 ml->level, mod);
520 ast_free(ml);
521 return CLI_SUCCESS;
522 }
523
524 if (ml) {
525 if ((atleast && newlevel < ml->level) || ml->level == newlevel) {
526 ast_cli(a->fd, "Core %s is still %u for '%s'.\n", handler_name, ml->level, mod);
527 AST_RWLIST_UNLOCK(modules);
528 return CLI_SUCCESS;
529 }
530 oldval = ml->level;
531 ml->level = newlevel;
532 } else {
533 ml = ast_calloc(1, sizeof(*ml) + strlen(mod) + 1);
534 if (!ml) {
535 AST_RWLIST_UNLOCK(modules);
536 return CLI_FAILURE;
537 }
538 oldval = ml->level;
539 ml->level = newlevel;
540 strcpy(ml->module, mod);
541 AST_RWLIST_INSERT_TAIL(modules, ml, entry);
542 }
543 ast_set_flag64(&ast_options, module_option);
544
545 ast_cli(a->fd, "Core %s was %d and has been set to %u for '%s'.\n", handler_name,
546 oldval, ml->level, ml->module);
547
548 AST_RWLIST_UNLOCK(modules);
549
550 return CLI_SUCCESS;
551 }
552 }
553
554 /* Update global debug level */
555 if (!newlevel) {
556 /* Specified level was 0 or off. */
557 AST_RWLIST_WRLOCK(modules);
558 while ((ml = AST_RWLIST_REMOVE_HEAD(modules, entry))) {
559 ast_free(ml);
560 }
561 ast_clear_flag64(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
562 AST_RWLIST_UNLOCK(modules);
563 }
564 oldval = *core_option;
565 if (!atleast || newlevel > *core_option) {
566 *core_option = newlevel;
567 }
568
569 /* Report debug level status */
570 status_debug_verbose(a, handler, oldval, *core_option);
571
572 return CLI_SUCCESS;
573 }
574
575 static char *handle_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
576 {
577 int atleast = 0;
578 const char *argv3 = a->argv ? S_OR(a->argv[3], "") : "";
579
580 switch (cmd) {
581 case CLI_INIT:
582 e->command = "core set debug";
583 e->usage =
584 "Usage: core set debug [atleast] <level> [module]\n"
585 " core set debug off\n"
586 "\n"
587 " Sets level of debug messages to be displayed or\n"
588 " sets a module name to display debug messages from.\n"
589 " 0 or off means no messages should be displayed.\n"
590 " Equivalent to -d[d[...]] on startup\n";
591 return NULL;
592
593 case CLI_GENERATE:
594 if (!strcasecmp(argv3, "category")) {
595 return NULL;
596 }
597
598 if (!strcasecmp(argv3, "atleast")) {
599 atleast = 1;
600 }
601 if (a->pos == 3 || (a->pos == 4 && atleast)) {
602 const char *pos = a->pos == 3 ? argv3 : S_OR(a->argv[4], "");
603 int numbermatch = (ast_strlen_zero(pos) || strchr("123456789", pos[0])) ? 0 : 21;
604
605 if (a->n < 21 && numbermatch == 0) {
606 return complete_number(pos, 0, 0x7fffffff, a->n);
607 } else if (pos[0] == '0') {
608 if (a->n == 0) {
609 return ast_strdup("0");
610 }
611 } else if (a->n == (21 - numbermatch)) {
612 if (a->pos == 3 && !strncasecmp(argv3, "off", strlen(argv3))) {
613 return ast_strdup("off");
614 } else if (a->pos == 3 && !strncasecmp(argv3, "atleast", strlen(argv3))) {
615 return ast_strdup("atleast");
616 }
617 } else if (a->n == (22 - numbermatch) && a->pos == 3 && ast_strlen_zero(argv3)) {
618 return ast_strdup("atleast");
619 }
620 } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off") && strcasecmp(argv3, "channel"))
621 || (a->pos == 5 && atleast)) {
622 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_RUNNING);
623 }
624 return NULL;
625 }
626 /* all the above return, so we proceed with the handler.
627 * we are guaranteed to be called with argc >= e->args;
628 */
629
630 return handle_debug_or_trace(DEBUG_HANDLER, e, cmd, a);
631 }
632
633 static char *handle_trace(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
634 {
635 int atleast = 0;
636 const char *argv3 = a->argv ? S_OR(a->argv[3], "") : "";
637
638 switch (cmd) {
639 case CLI_INIT:
640 e->command = "core set trace";
641 e->usage =
642 "Usage: core set trace [atleast] <level> [module]\n"
643 " core set trace off\n"
644 "\n"
645 " Sets level of trace messages to be displayed or\n"
646 " sets a module name to display trace messages from.\n"
647 " 0 or off means no messages should be displayed.\n";
648 return NULL;
649
650 case CLI_GENERATE:
651 if (!strcasecmp(argv3, "atleast")) {
652 atleast = 1;
653 }
654 if (a->pos == 3 || (a->pos == 4 && atleast)) {
655 const char *pos = a->pos == 3 ? argv3 : S_OR(a->argv[4], "");
656 int numbermatch = (ast_strlen_zero(pos) || strchr("123456789", pos[0])) ? 0 : 21;
657
658 if (a->n < 21 && numbermatch == 0) {
659 return complete_number(pos, 0, 0x7fffffff, a->n);
660 } else if (pos[0] == '0') {
661 if (a->n == 0) {
662 return ast_strdup("0");
663 }
664 } else if (a->n == (21 - numbermatch)) {
665 if (a->pos == 3 && !strncasecmp(argv3, "off", strlen(argv3))) {
666 return ast_strdup("off");
667 } else if (a->pos == 3 && !strncasecmp(argv3, "atleast", strlen(argv3))) {
668 return ast_strdup("atleast");
669 }
670 } else if (a->n == (22 - numbermatch) && a->pos == 3 && ast_strlen_zero(argv3)) {
671 return ast_strdup("atleast");
672 }
673 } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off") && strcasecmp(argv3, "channel"))
674 || (a->pos == 5 && atleast)) {
675 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_RUNNING);
676 }
677 return NULL;
678 }
679 /* all the above return, so we proceed with the handler.
680 * we are guaranteed to be called with argc >= e->args;
681 */
682
683 return handle_debug_or_trace(TRACE_HANDLER, e, cmd, a);
684 }
685
686 static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
687 {
688 int oldval;
689 int newlevel;
690 int atleast = 0;
691 int silent = 0;
692 const char *argv3 = a->argv ? S_OR(a->argv[3], "") : "";
693
694 switch (cmd) {
695 case CLI_INIT:
696 e->command = "core set verbose";
697 e->usage =
698 "Usage: core set verbose [atleast] <level> [silent]\n"
699 " core set verbose off\n"
700 "\n"
701 " Sets level of verbose messages to be displayed.\n"
702 " 0 or off means no verbose messages should be displayed.\n"
703 " The silent option means the command does not report what\n"
704 " happened to the verbose level.\n"
705 " Equivalent to -v[v[...]] on startup\n";
706 return NULL;
707
708 case CLI_GENERATE:
709 if (!strcasecmp(argv3, "atleast")) {
710 atleast = 1;
711 }
712 if (a->pos == 3 || (a->pos == 4 && atleast)) {
713 const char *pos = a->pos == 3 ? argv3 : S_OR(a->argv[4], "");
714 int numbermatch = (ast_strlen_zero(pos) || strchr("123456789", pos[0])) ? 0 : 21;
715
716 if (a->n < 21 && numbermatch == 0) {
717 return complete_number(pos, 0, 0x7fffffff, a->n);
718 } else if (pos[0] == '0') {
719 if (a->n == 0) {
720 return ast_strdup("0");
721 }
722 } else if (a->n == (21 - numbermatch)) {
723 if (a->pos == 3 && !strncasecmp(argv3, "off", strlen(argv3))) {
724 return ast_strdup("off");
725 } else if (a->pos == 3 && !strncasecmp(argv3, "atleast", strlen(argv3))) {
726 return ast_strdup("atleast");
727 }
728 } else if (a->n == (22 - numbermatch) && a->pos == 3 && ast_strlen_zero(argv3)) {
729 return ast_strdup("atleast");
730 }
731 } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off"))
732 || (a->pos == 5 && atleast)) {
733 const char *pos = S_OR(a->argv[a->pos], "");
734
735 if (a->n == 0 && !strncasecmp(pos, "silent", strlen(pos))) {
736 return ast_strdup("silent");
737 }
738 }
739 return NULL;
740 }
741 /* all the above return, so we proceed with the handler.
742 * we are guaranteed to be called with argc >= e->args;
743 */
744
745 if (a->argc <= e->args) {
746 return CLI_SHOWUSAGE;
747 }
748
749 if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args], "off")) {
750 newlevel = 0;
751 } else {
752 if (!strcasecmp(a->argv[e->args], "atleast")) {
753 atleast = 1;
754 }
755 if (a->argc == e->args + atleast + 2
756 && !strcasecmp(a->argv[e->args + atleast + 1], "silent")) {
757 silent = 1;
758 }
759 if (a->argc != e->args + atleast + silent + 1) {
760 return CLI_SHOWUSAGE;
761 }
762 if (sscanf(a->argv[e->args + atleast], "%30d", &newlevel) != 1) {
763 return CLI_SHOWUSAGE;
764 }
765 }
766
767 /* Update verbose level */
768 oldval = ast_verb_console_get();
769 if (!atleast || newlevel > oldval) {
770 ast_verb_console_set(newlevel);
771 } else {
772 newlevel = oldval;
773 }
774
775 if (silent) {
776 /* Be silent after setting the level. */
777 return CLI_SUCCESS;
778 }
779
780 /* Report verbose level status */
781 status_debug_verbose(a, VERBOSE_HANDLER, oldval, newlevel);
782
783 return CLI_SUCCESS;
784 }
785
786 static char *handle_logger_mute(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
787 {
788 switch (cmd) {
789 case CLI_INIT:
790 e->command = "logger mute";
791 e->usage =
792 "Usage: logger mute\n"
793 " Disables logging output to the current console, making it possible to\n"
794 " gather information without being disturbed by scrolling lines.\n";
795 return NULL;
796 case CLI_GENERATE:
797 return NULL;
798 }
799
800 if (a->argc < 2 || a->argc > 3)
801 return CLI_SHOWUSAGE;
802
803 if (a->argc == 3 && !strcasecmp(a->argv[2], "silent"))
804 ast_console_toggle_mute(a->fd, 1);
805 else
806 ast_console_toggle_mute(a->fd, 0);
807
808 return CLI_SUCCESS;
809 }
810
811 static char *handle_refresh(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
812 {
813 static const char * const completions[] = { "recursively", NULL };
814 int res;
815 /* "module refresh <mod>" */
816 switch (cmd) {
817 case CLI_INIT:
818 e->command = "module refresh";
819 e->usage =
820 "Usage: module refresh <module name> [recursively]\n"
821 " Unloads and loads the specified module into Asterisk.\n"
822 " 'recursively' will attempt to unload any modules with\n"
823 " dependencies on this module for you and load them again\n"
824 " afterwards.\n";
825 return NULL;
826
827 case CLI_GENERATE:
828 if (a->pos == e->args) {
829 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_UNLOAD);
830 } else if (a->pos == e->args + 1) {
831 return ast_cli_complete(a->word, completions, a->n);
832 }
833 return NULL;
834 }
835 if (a->argc < 3 || a->argc > 4) {
836 return CLI_SHOWUSAGE;
837 }
838
839 res = ast_refresh_resource(a->argv[e->args], AST_FORCE_SOFT, a->argc == 4 && !strcasecmp(a->argv[3], "recursively"));
840 if (res) {
841 ast_cli(a->fd, "Unable to %s resource %s\n", res > 0 ? "unload" : "load", a->argv[e->args]);
842 return CLI_FAILURE;
843 }
844 ast_cli(a->fd, "Unloaded and loaded %s\n", a->argv[e->args]);
845 return CLI_SUCCESS;
846 }
847
848 static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
849 {
850 /* "module unload mod_1 [mod_2 .. mod_N]" */
851 int x;
852 int force = AST_FORCE_SOFT;
853 const char *s;
854
855 switch (cmd) {
856 case CLI_INIT:
857 e->command = "module unload";
858 e->usage =
859 "Usage: module unload [-f|-h] <module_1> [<module_2> ... ]\n"
860 " Unloads the specified module from Asterisk. The -f\n"
861 " option causes the module to be unloaded even if it is\n"
862 " in use (may cause a crash) and the -h module causes the\n"
863 " module to be unloaded even if the module says it cannot, \n"
864 " which almost always will cause a crash.\n";
865 return NULL;
866
867 case CLI_GENERATE:
868 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_UNLOAD);
869 }
870 if (a->argc < e->args + 1)
871 return CLI_SHOWUSAGE;
872 x = e->args; /* first argument */
873 s = a->argv[x];
874 if (s[0] == '-') {
875 if (s[1] == 'f')
876 force = AST_FORCE_FIRM;
877 else if (s[1] == 'h')
878 force = AST_FORCE_HARD;
879 else
880 return CLI_SHOWUSAGE;
881 if (a->argc < e->args + 2) /* need at least one module name */
882 return CLI_SHOWUSAGE;
883 x++; /* skip this argument */
884 }
885
886 for (; x < a->argc; x++) {
887 if (ast_unload_resource(a->argv[x], force)) {
888 ast_cli(a->fd, "Unable to unload resource %s\n", a->argv[x]);
889 return CLI_FAILURE;
890 }
891 ast_cli(a->fd, "Unloaded %s\n", a->argv[x]);
892 }
893
894 return CLI_SUCCESS;
895 }
896
897 #define MODLIST_FORMAT "%-30s %-40.40s %-10d %-11s %13s\n"
898 #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s %-11s %13s\n"
899
900 AST_MUTEX_DEFINE_STATIC(climodentrylock);
901 static int climodentryfd = -1;
902
903 static int modlist_modentry(const char *module, const char *description,
904 int usecnt, const char *status, const char *like,
905 enum ast_module_support_level support_level)
906 {
907 /* Comparing the like with the module */
908 if (strcasestr(module, like) ) {
909 ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt,
910 status, ast_module_support_level_to_string(support_level));
911 return 1;
912 }
913 return 0;
914 }
915
916 static void print_uptimestr(int fd, struct timeval timeval, const char *prefix, int printsec)
917 {
918 int x; /* the main part - years, weeks, etc. */
919 struct ast_str *out;
920
921 #define SECOND (1)
922 #define MINUTE (SECOND*60)
923 #define HOUR (MINUTE*60)
924 #define DAY (HOUR*24)
925 #define WEEK (DAY*7)
926 #define YEAR (DAY*365)
927 #define NEEDCOMMA(x) ((x) ? ", " : "") /* define if we need a comma */
928 if (timeval.tv_sec < 0) /* invalid, nothing to show */
929 return;
930
931 if (printsec) { /* plain seconds output */
932 ast_cli(fd, "%s%lu\n", prefix, (u_long)timeval.tv_sec);
933 return;
934 }
935 out = ast_str_alloca(256);
936 if (timeval.tv_sec > YEAR) {
937 x = (timeval.tv_sec / YEAR);
938 timeval.tv_sec -= (x * YEAR);
939 ast_str_append(&out, 0, "%d year%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
940 }
941 if (timeval.tv_sec > WEEK) {
942 x = (timeval.tv_sec / WEEK);
943 timeval.tv_sec -= (x * WEEK);
944 ast_str_append(&out, 0, "%d week%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
945 }
946 if (timeval.tv_sec > DAY) {
947 x = (timeval.tv_sec / DAY);
948 timeval.tv_sec -= (x * DAY);
949 ast_str_append(&out, 0, "%d day%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
950 }
951 if (timeval.tv_sec > HOUR) {
952 x = (timeval.tv_sec / HOUR);
953 timeval.tv_sec -= (x * HOUR);
954 ast_str_append(&out, 0, "%d hour%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
955 }
956 if (timeval.tv_sec > MINUTE) {
957 x = (timeval.tv_sec / MINUTE);
958 timeval.tv_sec -= (x * MINUTE);
959 ast_str_append(&out, 0, "%d minute%s%s", x, ESS(x), NEEDCOMMA(timeval.tv_sec));
960 }
961 x = timeval.tv_sec;
962 if (x > 0 || ast_str_strlen(out) == 0) {
963 /* if there is nothing, print 0 seconds */
964 ast_str_append(&out, 0, "%d second%s", x, ESS(x));
965 }
966 ast_cli(fd, "%s%s\n", prefix, ast_str_buffer(out));
967 }
968
969 static struct ast_cli_entry *cli_next(struct ast_cli_entry *e)
970 {
971 if (e) {
972 return AST_LIST_NEXT(e, list);
973 } else {
974 return AST_LIST_FIRST(&helpers);
975 }
976 }
977
978 static char * handle_showuptime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
979 {
980 struct timeval curtime = ast_tvnow();
981 int printsec;
982
983 switch (cmd) {
984 case CLI_INIT:
985 e->command = "core show uptime [seconds]";
986 e->usage =
987 "Usage: core show uptime [seconds]\n"
988 " Shows Asterisk uptime information.\n"
989 " The seconds word returns the uptime in seconds only.\n";
990 return NULL;
991
992 case CLI_GENERATE:
993 return NULL;
994 }
995 /* regular handler */
996 if (a->argc == e->args && !strcasecmp(a->argv[e->args-1],"seconds"))
997 printsec = 1;
998 else if (a->argc == e->args-1)
999 printsec = 0;
1000 else
1001 return CLI_SHOWUSAGE;
1002 if (ast_startuptime.tv_sec) {
1003 print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime: ", printsec);
1004 }
1005 if (ast_lastreloadtime.tv_sec) {
1006 print_uptimestr(a->fd, ast_tvsub(curtime, ast_lastreloadtime), "Last reload: ", printsec);
1007 }
1008 return CLI_SUCCESS;
1009 }
1010
1011 static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1012 {
1013 const char *like;
1014
1015 switch (cmd) {
1016 case CLI_INIT:
1017 e->command = "module show [like]";
1018 e->usage =
1019 "Usage: module show [like keyword]\n"
1020 " Shows Asterisk modules currently in use, and usage statistics.\n";
1021 return NULL;
1022
1023 case CLI_GENERATE:
1024 if (a->pos == e->args) {
1025 return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, AST_MODULE_HELPER_LOADED);
1026 } else {
1027 return NULL;
1028 }
1029 }
1030 /* all the above return, so we proceed with the handler.
1031 * we are guaranteed to have argc >= e->args
1032 */
1033 if (a->argc == e->args - 1)
1034 like = "";
1035 else if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args-1], "like") )
1036 like = a->argv[e->args];
1037 else
1038 return CLI_SHOWUSAGE;
1039
1040 ast_mutex_lock(&climodentrylock);
1041 climodentryfd = a->fd; /* global, protected by climodentrylock */
1042 ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count", "Status", "Support Level");
1043 ast_cli(a->fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
1044 climodentryfd = -1;
1045 ast_mutex_unlock(&climodentrylock);
1046 return CLI_SUCCESS;
1047 }
1048 #undef MODLIST_FORMAT
1049 #undef MODLIST_FORMAT2
1050
1051 static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1052 {
1053 static const char * const completions[] = { "seconds", NULL };
1054 struct timeval curtime = ast_tvnow();
1055 int showuptime, printsec;
1056
1057 switch (cmd) {
1058 case CLI_INIT:
1059 e->command = "core show calls [uptime]";
1060 e->usage =
1061 "Usage: core show calls [uptime [seconds]]\n"
1062 " Lists number of currently active calls and total number of calls\n"
1063 " processed through PBX since last restart. If 'uptime' is specified\n"
1064 " the system uptime is also displayed. If 'seconds' is specified in\n"
1065 " addition to 'uptime', the system uptime is displayed in seconds.\n";
1066 return NULL;
1067
1068 case CLI_GENERATE:
1069 if (a->pos != e->args)
1070 return NULL;
1071 return ast_cli_complete(a->word, completions, a->n);
1072 }
1073
1074 /* regular handler */
1075 if (a->argc >= e->args && !strcasecmp(a->argv[e->args-1],"uptime")) {
1076 showuptime = 1;
1077
1078 if (a->argc == e->args+1 && !strcasecmp(a->argv[e->args],"seconds"))
1079 printsec = 1;
1080 else if (a->argc == e->args)
1081 printsec = 0;
1082 else
1083 return CLI_SHOWUSAGE;
1084 } else if (a->argc == e->args-1) {
1085 showuptime = 0;
1086 printsec = 0;
1087 } else
1088 return CLI_SHOWUSAGE;
1089
1090 if (ast_option_maxcalls) {
1091 ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
1092 ast_active_calls(), ast_option_maxcalls, ESS(ast_active_calls()),
1093 ((double)ast_active_calls() / (double)ast_option_maxcalls) * 100.0);
1094 } else {
1095 ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
1096 }
1097
1098 ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
1099
1100 if (ast_startuptime.tv_sec && showuptime) {
1101 print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime: ", printsec);
1102 }
1103
1104 return RESULT_SUCCESS;
1105 }
1106
1107 static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1108 {
1109 #define FORMAT_STRING "%-64.64s %-32.32s %-7.7s %-30.30s\n"
1110 #define FORMAT_STRING2 "%-64.64s %-32.32s %-7.7s %-30.30s\n"
1111 #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%s!%d!%s!%s!%s\n"
1112 #define VERBOSE_FORMAT_STRING "%-80.80s %-24.24s %-24.24s %4d %-7.7s %-12.12s %-25.25s %-15.15s %8.8s %-11.11s %-11.11s %-20.20s\n"
1113 #define VERBOSE_FORMAT_STRING2 "%-80.80s %-24.24s %-24.24s %-4.4s %-7.7s %-12.12s %-25.25s %-15.15s %8.8s %-11.11s %-11.11s %-20.20s\n"
1114
1115 struct ao2_container *channels;
1116 struct ao2_iterator it_chans;
1117 struct ast_channel_snapshot *cs;
1118 int numchans = 0, concise = 0, verbose = 0, count = 0;
1119
1120 switch (cmd) {
1121 case CLI_INIT:
1122 e->command = "core show channels [concise|verbose|count]";
1123 e->usage =
1124 "Usage: core show channels [concise|verbose|count]\n"
1125 " Lists currently defined channels and some information about them. If\n"
1126 " 'concise' is specified, the format is abridged and in a more easily\n"
1127 " machine parsable format. If 'verbose' is specified, the output includes\n"
1128 " more and longer fields. If 'count' is specified only the channel and call\n"
1129 " count is output.\n";
1130 return NULL;
1131
1132 case CLI_GENERATE:
1133 return NULL;
1134 }
1135
1136 if (a->argc == e->args) {
1137 if (!strcasecmp(a->argv[e->args-1],"concise"))
1138 concise = 1;
1139 else if (!strcasecmp(a->argv[e->args-1],"verbose"))
1140 verbose = 1;
1141 else if (!strcasecmp(a->argv[e->args-1],"count"))
1142 count = 1;
1143 else
1144 return CLI_SHOWUSAGE;
1145 } else if (a->argc != e->args - 1)
1146 return CLI_SHOWUSAGE;
1147
1148 channels = ast_channel_cache_by_name();
1149
1150 if (!count) {
1151 if (!concise && !verbose)
1152 ast_cli(a->fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
1153 else if (verbose)
1154 ast_cli(a->fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
1155 "CallerID", "Duration", "Accountcode", "PeerAccount", "BridgeID");
1156 }
1157
1158 it_chans = ao2_iterator_init(channels, 0);
1159 for (; (cs = ao2_iterator_next(&it_chans)); ao2_ref(cs, -1)) {
1160 char durbuf[16] = "-";
1161
1162 if (!count) {
1163 if ((concise || verbose) && !ast_tvzero(cs->base->creationtime)) {
1164 int duration = (int)(ast_tvdiff_ms(ast_tvnow(), cs->base->creationtime) / 1000);
1165 if (verbose) {
1166 int durh = duration / 3600;
1167 int durm = (duration % 3600) / 60;
1168 int durs = duration % 60;
1169 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
1170 } else {
1171 snprintf(durbuf, sizeof(durbuf), "%d", duration);
1172 }
1173 }
1174 if (concise) {
1175 ast_cli(a->fd, CONCISE_FORMAT_STRING, cs->base->name, cs->dialplan->context, cs->dialplan->exten, cs->dialplan->priority, ast_state2str(cs->state),
1176 S_OR(cs->dialplan->appl, "(None)"),
1177 cs->dialplan->data,
1178 cs->caller->number,
1179 cs->base->accountcode,
1180 cs->peer->account,
1181 cs->amaflags,
1182 durbuf,
1183 cs->bridge->id,
1184 cs->base->uniqueid);
1185 } else if (verbose) {
1186 ast_cli(a->fd, VERBOSE_FORMAT_STRING, cs->base->name, cs->dialplan->context, cs->dialplan->exten, cs->dialplan->priority, ast_state2str(cs->state),
1187 S_OR(cs->dialplan->appl, "(None)"),
1188 S_OR(cs->dialplan->data, "(Empty)"),
1189 cs->caller->number,
1190 durbuf,
1191 cs->base->accountcode,
1192 cs->peer->account,
1193 cs->bridge->id);
1194 } else {
1195 char locbuf[40] = "(None)";
1196 char appdata[40] = "(None)";
1197
1198 if (!ast_strlen_zero(cs->dialplan->context) && !ast_strlen_zero(cs->dialplan->exten)) {
1199 snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", cs->dialplan->exten, cs->dialplan->context, cs->dialplan->priority);
1200 }
1201 if (!ast_strlen_zero(cs->dialplan->appl)) {
1202 snprintf(appdata, sizeof(appdata), "%s(%s)", cs->dialplan->appl, S_OR(cs->dialplan->data, ""));
1203 }
1204 ast_cli(a->fd, FORMAT_STRING, cs->base->name, locbuf, ast_state2str(cs->state), appdata);
1205 }
1206 }
1207 }
1208 ao2_iterator_destroy(&it_chans);
1209
1210 if (!concise) {
1211 numchans = ast_active_channels();
1212 ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
1213 if (ast_option_maxcalls)
1214 ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
1215 ast_active_calls(), ast_option_maxcalls, ESS(ast_active_calls()),
1216 ((double)ast_active_calls() / (double)ast_option_maxcalls) * 100.0);
1217 else
1218 ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
1219
1220 ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
1221 }
1222 ao2_ref(channels, -1);
1223
1224 return CLI_SUCCESS;
1225
1226 #undef FORMAT_STRING
1227 #undef FORMAT_STRING2
1228 #undef CONCISE_FORMAT_STRING
1229 #undef VERBOSE_FORMAT_STRING
1230 #undef VERBOSE_FORMAT_STRING2
1231 }
1232
1233 static int channel_match_by_regex(const char *channel_name, const void *data)
1234 {
1235 return regexec(data, channel_name, 0, NULL, 0);
1236 }
1237
1238 static int channel_match_by_glob(const char *channel_name, const void *pattern)
1239 {
1240 #if defined(HAVE_FNM_CASEFOLD)
1241 return fnmatch(pattern, channel_name, FNM_NOESCAPE | FNM_PATHNAME | FNM_CASEFOLD);
1242 #else
1243 char *lower_channel_name = ast_str_to_lower(ast_strdup(channel_name));
1244 if (lower_channel_name) {
1245 int res = fnmatch(pattern, lower_channel_name, FNM_NOESCAPE | FNM_PATHNAME);
1246 ast_free(lower_channel_name);
1247 return res;
1248 }
1249 return FNM_NOMATCH;
1250 #endif
1251 }
1252
1253 static int channel_hangup_matches(
1254 struct ast_cli_args *a,
1255 int (*matchfn)(const char *, const void *),
1256 const void *data)
1257 {
1258 struct ao2_container *cached_channels;
1259 struct ao2_iterator iter;
1260 struct ast_channel_snapshot *snapshot;
1261 struct ast_channel *c;
1262 int matched = 0;
1263
1264 cached_channels = ast_channel_cache_all();
1265
1266 iter = ao2_iterator_init(cached_channels, 0);
1267 for (; (snapshot = ao2_iterator_next(&iter)); ao2_ref(snapshot, -1)) {
1268 if ((!matchfn || !matchfn(snapshot->base->name, data))
1269 && (c = ast_channel_get_by_name(snapshot->base->name))) {
1270 ast_cli(a->fd, "Requested Hangup on channel '%s'\n", snapshot->base->name);
1271 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
1272 c = ast_channel_unref(c);
1273 matched++;
1274 }
1275 }
1276 ao2_iterator_destroy(&iter);
1277 ao2_ref(cached_channels, -1);
1278
1279 return matched;
1280 }
1281
1282 #define arg_looks_like_regex(n) \
1283 (*n == '/' && n[strlen(n) - 1] == '/')
1284
1285 #define arg_looks_like_glob(n) \
1286 (strcspn(n, "?*[") < strlen(n))
1287
1288 static char *handle_softhangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1289 {
1290 struct ast_channel *c = NULL;
1291 static const char * const completions[] = { "all", NULL };
1292 char *complete = NULL;
1293 int x;
1294
1295 switch (cmd) {
1296 case CLI_INIT:
1297 e->command = "channel request hangup";
1298 e->usage =
1299 "Usage: channel request hangup <all>|<channel> [<channel> ...]\n"
1300 " Request that one or more channels be hung up. The hangup takes\n"
1301 " effect the next time the driver reads or writes from the channel.\n\n"
1302 " If 'all' is specified instead of a channel name, all channels\n"
1303 " will see the hangup request.\n\n"
1304 " A POSIX Extended Regular Expression can be provided in the place\n"
1305 " of a fixed channel name by wrapping it in forward slashes\n"
1306 " (e.g. /^PJSIP.*/). Note that the expression will match any part\n"
1307 " of the channel name unless anchored explicitly by ^ and/or $.\n\n"
1308 " Finally, wildcards (*) and other glob-like characters can also\n"
1309 " be used to match more than one channel. Similar to how path globs\n"
1310 " behave, a forward slash cannot be matched with a wildcard or\n"
1311 " bracket expression. In other words, if you want to hangup all\n"
1312 " Local channels, you must specify Local/* and not Loc*.\n";
1313 return NULL;
1314 case CLI_GENERATE:
1315 if (a->pos < e->args) {
1316 return NULL;
1317 } else if (a->pos == e->args) {
1318 complete = ast_cli_complete(a->word, completions, a->n);
1319 }
1320 if (!complete) {
1321 complete = ast_complete_channels(a->line, a->word, a->pos, a->n - 1, a->pos);
1322 }
1323 return complete;
1324 }
1325
1326 if (a->argc < 4) {
1327 return CLI_SHOWUSAGE;
1328 }
1329
1330 if (!strcasecmp(a->argv[3], "all")) {
1331 channel_hangup_matches(a, NULL, NULL);
1332 return CLI_SUCCESS;
1333 }
1334
1335 for (x = e->args; x < a->argc; x++) {
1336 /* Try to find a literal channel name first */
1337 if ((c = ast_channel_get_by_name(a->argv[x]))) {
1338 ast_channel_lock(c);
1339 ast_cli(a->fd, "Requested Hangup on channel '%s'\n", ast_channel_name(c));
1340 ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
1341 ast_channel_unlock(c);
1342 c = ast_channel_unref(c);
1343 continue;
1344 }
1345
1346 if (arg_looks_like_regex(a->argv[x])) {
1347 char *pattern = ast_strdup(a->argv[x]);
1348 regex_t re;
1349 int res;
1350
1351 if (!pattern) {
1352 return CLI_FAILURE;
1353 }
1354
1355 pattern[strlen(pattern) - 1] = 0;
1356 res = regcomp(&re, &pattern[1], REG_EXTENDED | REG_ICASE | REG_NOSUB);
1357 ast_free(pattern);
1358 if (res) {
1359 char errbuf[MAX_REGEX_ERROR_LEN];
1360 regerror(res, &re, errbuf, sizeof(errbuf));
1361 ast_cli(a->fd, "%s is not a valid POSIX Extended Regular Expression: %s\n",
1362 a->argv[x], errbuf);
1363 continue;
1364 }
1365
1366 if (!channel_hangup_matches(a, channel_match_by_regex, &re)) {
1367 ast_cli(a->fd, "%s did not match a known channel\n", a->argv[x]);
1368 }
1369 regfree(&re);
1370 } else if (arg_looks_like_glob(a->argv[x])) {
1371 #if defined(HAVE_FNM_CASEFOLD)
1372 if (!channel_hangup_matches(a, channel_match_by_glob, a->argv[x])) {
1373 ast_cli(a->fd, "%s did not match a known channel\n", a->argv[x]);
1374 }
1375 #else
1376 char *pattern = ast_str_to_lower(ast_strdup(a->argv[x]));
1377 if (pattern) {
1378 if (!channel_hangup_matches(a, channel_match_by_glob, pattern)) {
1379 ast_cli(a->fd, "%s did not match a known channel\n", a->argv[x]);
1380 }
1381 ast_free(pattern);
1382 } else {
1383 return CLI_FAILURE;
1384 }
1385 #endif
1386 } else {
1387 ast_cli(a->fd, "%s is not a known channel\n", a->argv[x]);
1388 }
1389 }
1390
1391 return CLI_SUCCESS;
1392 }
1393
1394 /*! \brief handles CLI command 'cli show permissions' */
1395 static char *handle_cli_show_permissions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1396 {
1397 struct usergroup_cli_perm *cp;
1398 struct cli_perm *perm;
1399 struct passwd *pw = NULL;
1400 struct group *gr = NULL;
1401
1402 switch (cmd) {
1403 case CLI_INIT:
1404 e->command = "cli show permissions";
1405 e->usage =
1406 "Usage: cli show permissions\n"
1407 " Shows CLI configured permissions.\n";
1408 return NULL;
1409 case CLI_GENERATE:
1410 return NULL;
1411 }
1412
1413 AST_RWLIST_RDLOCK(&cli_perms);
1414 AST_LIST_TRAVERSE(&cli_perms, cp, list) {
1415 if (cp->uid >= 0) {
1416 pw = getpwuid(cp->uid);
1417 if (pw) {
1418 ast_cli(a->fd, "user: %s [uid=%d]\n", pw->pw_name, cp->uid);
1419 }
1420 } else {
1421 gr = getgrgid(cp->gid);
1422 if (gr) {
1423 ast_cli(a->fd, "group: %s [gid=%d]\n", gr->gr_name, cp->gid);
1424 }
1425 }
1426 ast_cli(a->fd, "Permissions:\n");
1427 if (cp->perms) {
1428 AST_LIST_TRAVERSE(cp->perms, perm, list) {
1429 ast_cli(a->fd, "\t%s -> %s\n", perm->permit ? "permit" : "deny", perm->command);
1430 }
1431 }
1432 ast_cli(a->fd, "\n");
1433 }
1434 AST_RWLIST_UNLOCK(&cli_perms);
1435
1436 return CLI_SUCCESS;
1437 }
1438
1439 /*! \brief handles CLI command 'cli reload permissions' */
1440 static char *handle_cli_reload_permissions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1441 {
1442 switch (cmd) {
1443 case CLI_INIT:
1444 e->command = "cli reload permissions";
1445 e->usage =
1446 "Usage: cli reload permissions\n"
1447 " Reload the 'cli_permissions.conf' file.\n";
1448 return NULL;
1449 case CLI_GENERATE:
1450 return NULL;
1451 }
1452
1453 ast_cli_perms_init(1);
1454
1455 return CLI_SUCCESS;
1456 }
1457
1458 /*! \brief handles CLI command 'cli check permissions' */
1459 static char *handle_cli_check_permissions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1460 {
1461 struct passwd *pw = NULL;
1462 struct group *gr;
1463 int gid = -1, uid = -1;
1464 char command[AST_MAX_ARGS] = "";
1465 struct ast_cli_entry *ce = NULL;
1466 int found = 0;
1467 char *group, *tmp;
1468
1469 switch (cmd) {
1470 case CLI_INIT:
1471 e->command = "cli check permissions";
1472 e->usage =
1473 "Usage: cli check permissions {<username>|@<groupname>|<username>@<groupname>} [<command>]\n"
1474 " Check permissions config for a user@group or list the allowed commands for the specified user.\n"
1475 " The username or the groupname may be omitted.\n";
1476 return NULL;
1477 case CLI_GENERATE:
1478 if (a->pos >= 4) {
1479 return ast_cli_generator(a->line + strlen("cli check permissions") + strlen(a->argv[3]) + 1, a->word, a->n);
1480 }
1481 return NULL;
1482 }
1483
1484 if (a->argc < 4) {
1485 return CLI_SHOWUSAGE;
1486 }
1487
1488 tmp = ast_strdupa(a->argv[3]);
1489 group = strchr(tmp, '@');
1490 if (group) {
1491 gr = getgrnam(&group[1]);
1492 if (!gr) {
1493 ast_cli(a->fd, "Unknown group '%s'\n", &group[1]);
1494 return CLI_FAILURE;
1495 }
1496 group[0] = '\0';
1497 gid = gr->gr_gid;
1498 }
1499
1500 if (!group && ast_strlen_zero(tmp)) {
1501 ast_cli(a->fd, "You didn't supply a username\n");
1502 } else if (!ast_strlen_zero(tmp) && !(pw = getpwnam(tmp))) {
1503 ast_cli(a->fd, "Unknown user '%s'\n", tmp);
1504 return CLI_FAILURE;
1505 } else if (pw) {
1506 uid = pw->pw_uid;
1507 }
1508
1509 if (a->argc == 4) {
1510 while ((ce = cli_next(ce))) {
1511 /* Hide commands that start with '_' */
1512 if (ce->_full_cmd[0] == '_') {
1513 continue;
1514 }
1515 if (cli_has_permissions(uid, gid, ce->_full_cmd)) {
1516 ast_cli(a->fd, "%30.30s %s\n", ce->_full_cmd, S_OR(ce->summary, "<no description available>"));
1517 found++;
1518 }
1519 }
1520 if (!found) {
1521 ast_cli(a->fd, "You are not allowed to run any command on Asterisk\n");
1522 }
1523 } else {
1524 ast_join(command, sizeof(command), a->argv + 4);
1525 ast_cli(a->fd, "%s '%s%s%s' is %s to run command: '%s'\n", uid >= 0 ? "User" : "Group", tmp,
1526 group && uid >= 0 ? "@" : "",
1527 group ? &group[1] : "",
1528 cli_has_permissions(uid, gid, command) ? "allowed" : "not allowed", command);
1529 }
1530
1531 return CLI_SUCCESS;
1532 }
1533
1534 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
1535
1536 static char *handle_commandmatchesarray(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1537 {
1538 char *buf, *obuf;
1539 int buflen = 2048;
1540 int len = 0;
1541 char **matches;
1542 int x, matchlen;
1543
1544 switch (cmd) {
1545 case CLI_INIT:
1546 e->command = "_command matchesarray";
1547 e->usage =
1548 "Usage: _command matchesarray \"<line>\" text \n"
1549 " This function is used internally to help with command completion and should.\n"
1550 " never be called by the user directly.\n";
1551 return NULL;
1552 case CLI_GENERATE:
1553 return NULL;
1554 }
1555
1556 if (a->argc != 4)
1557 return CLI_SHOWUSAGE;
1558 if (!(buf = ast_malloc(buflen)))
1559 return CLI_FAILURE;
1560 buf[len] = '\0';
1561 matches = ast_cli_completion_matches(a->argv[2], a->argv[3]);
1562 if (matches) {
1563 for (x=0; matches[x]; x++) {
1564 matchlen = strlen(matches[x]) + 1;
1565 if (len + matchlen >= buflen) {
1566 buflen += matchlen * 3;
1567 obuf = buf;
1568 if (!(buf = ast_realloc(obuf, buflen)))
1569 /* Memory allocation failure... Just free old buffer and be done */
1570 ast_free(obuf);
1571 }
1572 if (buf)
1573 len += sprintf( buf + len, "%s ", matches[x]);
1574 ast_free(matches[x]);
1575 matches[x] = NULL;
1576 }
1577 ast_free(matches);
1578 }
1579
1580 if (buf) {
1581 ast_cli(a->fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
1582 ast_free(buf);
1583 } else
1584 ast_cli(a->fd, "NULL\n");
1585
1586 return CLI_SUCCESS;
1587 }
1588
1589
1590 struct channel_set_debug_args {
1591 int fd;
1592 int is_off;
1593 };
1594
1595 static int channel_set_debug(void *obj, void *arg, void *data, int flags)
1596 {
1597 struct ast_channel *chan = obj;
1598 struct channel_set_debug_args *args = data;
1599
1600 ast_channel_lock(chan);
1601
1602 if (!(ast_channel_fin(chan) & DEBUGCHAN_FLAG) || !(ast_channel_fout(chan) & DEBUGCHAN_FLAG)) {
1603 if (args->is_off) {
1604 ast_channel_fin_set(chan, ast_channel_fin(chan) & ~DEBUGCHAN_FLAG);
1605 ast_channel_fout_set(chan, ast_channel_fout(chan) & ~DEBUGCHAN_FLAG);
1606 } else {
1607 ast_channel_fin_set(chan, ast_channel_fin(chan) | DEBUGCHAN_FLAG);
1608 ast_channel_fout_set(chan, ast_channel_fout(chan) | DEBUGCHAN_FLAG);
1609 }
1610 ast_cli(args->fd, "Debugging %s on channel %s\n", args->is_off ? "disabled" : "enabled",
1611 ast_channel_name(chan));
1612 }
1613
1614 ast_channel_unlock(chan);
1615
1616 return 0;
1617 }
1618
1619 static char *handle_core_set_debug_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1620 {
1621 struct ast_channel *c = NULL;
1622 static const char * const completions_all[] = { "all", NULL };
1623 static const char * const completions_off[] = { "off", NULL };
1624 struct channel_set_debug_args args = {
1625 .fd = a->fd,
1626 };
1627
1628 switch (cmd) {
1629 case CLI_INIT:
1630 e->command = "core set debug channel";
1631 e->usage =
1632 "Usage: core set debug channel <all|channel> [off]\n"
1633 " Enables/disables debugging on all or on a specific channel.\n";
1634 return NULL;
1635 case CLI_GENERATE:
1636 if (a->pos == 4) {
1637 char *complete = ast_cli_complete(a->word, completions_all, a->n);
1638 if (!complete) {
1639 complete = ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
1640 }
1641 return complete;
1642 } else if (a->pos == 5) {
1643 return ast_cli_complete(a->word, completions_off, a->n);
1644 }
1645
1646 return NULL;
1647 }
1648
1649 if (cmd == (CLI_HANDLER + 1000)) {
1650 /* called from handle_nodebugchan_deprecated */
1651 args.is_off = 1;
1652 } else if (a->argc == e->args + 2) {
1653 /* 'core set debug channel {all|chan_id}' */
1654 if (!strcasecmp(a->argv[e->args + 1], "off"))
1655 args.is_off = 1;
1656 else
1657 return CLI_SHOWUSAGE;
1658 } else if (a->argc != e->args + 1) {
1659 return CLI_SHOWUSAGE;
1660 }
1661
1662 if (!strcasecmp("all", a->argv[e->args])) {
1663 if (args.is_off) {
1664 global_fin &= ~DEBUGCHAN_FLAG;
1665 global_fout &= ~DEBUGCHAN_FLAG;
1666 } else {
1667 global_fin |= DEBUGCHAN_FLAG;
1668 global_fout |= DEBUGCHAN_FLAG;
1669 }
1670 ast_channel_callback(channel_set_debug, NULL, &args, OBJ_NODATA | OBJ_MULTIPLE);
1671 } else {
1672 if ((c = ast_channel_get_by_name(a->argv[e->args]))) {
1673 channel_set_debug(c, NULL, &args, 0);
1674 ast_channel_unref(c);
1675 } else {
1676 ast_cli(a->fd, "No such channel %s\n", a->argv[e->args]);
1677 }
1678 }
1679
1680 ast_cli(a->fd, "Debugging on new channels is %s\n", args.is_off ? "disabled" : "enabled");
1681
1682 return CLI_SUCCESS;
1683 }
1684
1685 static char *handle_debug_category(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1686 {
1687 const char *argv4 = a->argv ? S_OR(a->argv[4], "") : "";
1688 int offset = strncasecmp(argv4, "off", strlen(argv4)) ? 0 : 1;
1689
1690 switch (cmd) {
1691 case CLI_INIT:
1692 e->command = "core set debug category";
1693 e->usage =
1694 "Usage: core set debug category <category>[:<sublevel>] [category[:<sublevel] ...]\n"
1695 " core set debug category off [<category> [<category>] ...]\n\n"
1696 " Allows enabling and disabling debug logging categories.\n"
1697 " When a category is enabled all relevant debug messages are logged\n"
1698 " for a given category. However, if a sublevel is specified only\n"
1699 " those categorized messages at or below the coded debug sublevel\n"
1700 " are logged.\n";
1701 return NULL;
1702
1703 case CLI_GENERATE:
1704 if (a->pos < e->args) {
1705 return NULL;
1706 }
1707
1708 if (a->pos == 4 && offset) {
1709 ast_cli_completion_add(ast_strdup("off"));
1710 }
1711
1712 return ast_debug_category_complete(a->argv + 4,
1713 a->pos - e->args, a->word, a->n - 1);
1714 }
1715
1716 if (a->argc <= e->args) {
1717 return CLI_SHOWUSAGE;
1718 }
1719
1720 ast_debug_category_set_sublevels(a->argv + e->args + offset, a->argc - e->args - offset,
1721 offset ? AST_LOG_CATEGORY_DISABLED : AST_LOG_CATEGORY_ENABLED);
1722
1723 return CLI_SUCCESS;
1724 }
1725
1726 static char *handle_nodebugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1727 {
1728 char *res;
1729
1730 switch (cmd) {
1731 case CLI_INIT:
1732 e->command = "no debug channel";
1733 return NULL;
1734 case CLI_HANDLER:
1735 /* exit out of switch statement */
1736 break;
1737 default:
1738 return NULL;
1739 }
1740
1741 if (a->argc != e->args + 1)
1742 return CLI_SHOWUSAGE;
1743
1744 /* add a 'magic' value to the CLI_HANDLER command so that
1745 * handle_core_set_debug_channel() will act as if 'off'
1746 * had been specified as part of the command
1747 */
1748 res = handle_core_set_debug_channel(e, CLI_HANDLER + 1000, a);
1749
1750 return res;
1751 }
1752
1753 static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1754 {
1755 struct ast_channel *chan;
1756 struct timeval now;
1757 char cdrtime[256];
1758 struct ast_str *obuf;/*!< Buffer for CDR variables. */
1759 struct ast_str *output;/*!< Accumulation buffer for all output. */
1760 long elapsed_seconds=0;
1761 int hour=0, min=0, sec=0;
1762 struct ast_var_t *var;
1763 struct ast_str *write_transpath = ast_str_alloca(256);
1764 struct ast_str *read_transpath = ast_str_alloca(256);
1765 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
1766 struct ast_bridge *bridge;
1767 ast_callid callid;
1768 char callid_buf[32];
1769 int stream_num;
1770 RAII_VAR(char *, tenant_id, NULL, ast_free);
1771
1772 switch (cmd) {
1773 case CLI_INIT:
1774 e->command = "core show channel";
1775 e->usage =
1776 "Usage: core show channel <channel>\n"
1777 " Shows lots of information about the specified channel.\n";
1778 return NULL;
1779 case CLI_GENERATE:
1780 return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
1781 }
1782
1783 if (a->argc != 4) {
1784 return CLI_SHOWUSAGE;
1785 }
1786
1787 obuf = ast_str_thread_get(&ast_str_thread_global_buf, 16);
1788 if (!obuf) {
1789 return CLI_FAILURE;
1790 }
1791
1792 chan = ast_channel_get_by_name(a->argv[3]);
1793 if (!chan) {
1794 ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
1795
1796 return CLI_SUCCESS;
1797 }
1798
1799 output = ast_str_create(8192);
1800 if (!output) {
1801 ast_channel_unref(chan);
1802
1803 return CLI_FAILURE;
1804 }
1805
1806 now = ast_tvnow();
1807 ast_channel_lock(chan);
1808
1809 if (!ast_tvzero(ast_channel_creationtime(chan))) {
1810 elapsed_seconds = now.tv_sec - ast_channel_creationtime(chan).tv_sec;
1811 hour = elapsed_seconds / 3600;
1812 min = (elapsed_seconds % 3600) / 60;
1813 sec = elapsed_seconds % 60;
1814 snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
1815 } else {
1816 strcpy(cdrtime, "N/A");
1817 }
1818
1819 ast_translate_path_to_str(ast_channel_writetrans(chan), &write_transpath);
1820 ast_translate_path_to_str(ast_channel_readtrans(chan), &read_transpath);
1821
1822 bridge = ast_channel_get_bridge(chan);
1823 callid_buf[0] = '\0';
1824 callid = ast_channel_callid(chan);
1825 if (callid) {
1826 ast_callid_strnprint(callid_buf, sizeof(callid_buf), callid);
1827 }
1828
1829 if (!ast_strlen_zero(ast_channel_tenantid(chan))) {
1830 ast_asprintf(&tenant_id, " TenantID: %s\n", ast_channel_tenantid(chan));
1831 }
1832
1833 ast_str_append(&output, 0,
1834 " -- General --\n"
1835 " Name: %s\n"
1836 " Type: %s\n"
1837 " UniqueID: %s\n"
1838 " LinkedID: %s\n"
1839 "%s"
1840 " Caller ID: %s\n"
1841 " Caller ID Name: %s\n"
1842 "Connected Line ID: %s\n"
1843 "Connected Line ID Name: %s\n"
1844 "Eff. Connected Line ID: %s\n"
1845 "Eff. Connected Line ID Name: %s\n"
1846 " DNID Digits: %s\n"
1847 " Language: %s\n"
1848 " State: %s (%u)\n"
1849 " NativeFormats: %s\n"
1850 " WriteFormat: %s\n"
1851 " ReadFormat: %s\n"
1852 " WriteTranscode: %s %s\n"
1853 " ReadTranscode: %s %s\n"
1854 " Time to Hangup: %ld\n"
1855 " Elapsed Time: %s\n"
1856 " Bridge ID: %s\n"
1857 " -- PBX --\n"
1858 " Context: %s\n"
1859 " Extension: %s\n"
1860 " Priority: %d\n"
1861 " Call Group: %llu\n"
1862 " Pickup Group: %llu\n"
1863 " Application: %s\n"
1864 " Data: %s\n"
1865 " Call Identifier: %s\n",
1866 ast_channel_name(chan),
1867 ast_channel_tech(chan)->type,
1868 ast_channel_uniqueid(chan),
1869 ast_channel_linkedid(chan),
1870 !ast_strlen_zero(tenant_id) ? tenant_id : "",
1871 S_COR(ast_channel_caller(chan)->id.number.valid,
1872 ast_channel_caller(chan)->id.number.str, "(N/A)"),
1873 S_COR(ast_channel_caller(chan)->id.name.valid,
1874 ast_channel_caller(chan)->id.name.str, "(N/A)"),
1875 S_COR(ast_channel_connected(chan)->id.number.valid,
1876 ast_channel_connected(chan)->id.number.str, "(N/A)"),
1877 S_COR(ast_channel_connected(chan)->id.name.valid,
1878 ast_channel_connected(chan)->id.name.str, "(N/A)"),
1879 S_COR(ast_channel_connected_effective_id(chan).number.valid,
1880 ast_channel_connected_effective_id(chan).number.str, "(N/A)"),
1881 S_COR(ast_channel_connected_effective_id(chan).name.valid,
1882 ast_channel_connected_effective_id(chan).name.str, "(N/A)"),
1883 S_OR(ast_channel_dialed(chan)->number.str, "(N/A)"),
1884 ast_channel_language(chan),
1885 ast_state2str(ast_channel_state(chan)),
1886 ast_channel_state(chan),
1887 ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf),
1888 ast_format_get_name(ast_channel_writeformat(chan)),
1889 ast_format_get_name(ast_channel_readformat(chan)),
1890 ast_str_strlen(write_transpath) ? "Yes" : "No",
1891 ast_str_buffer(write_transpath),
1892 ast_str_strlen(read_transpath) ? "Yes" : "No",
1893 ast_str_buffer(read_transpath),
1894 (long)ast_channel_whentohangup(chan)->tv_sec,
1895 cdrtime,
1896 bridge ? bridge->uniqueid : "(Not bridged)",
1897 ast_channel_context(chan),
1898 ast_channel_exten(chan),
1899 ast_channel_priority(chan),
1900 ast_channel_callgroup(chan),
1901 ast_channel_pickupgroup(chan),
1902 S_OR(ast_channel_appl(chan), "(N/A)"),
1903 S_OR(ast_channel_data(chan), "(Empty)"),
1904 S_OR(callid_buf, "(None)")
1905 );
1906
1907 ast_str_append(&output, 0, " Variables:\n");
1908
1909 AST_LIST_TRAVERSE(ast_channel_varshead(chan), var, entries) {
1910 ast_str_append(&output, 0, "%s=%s\n", ast_var_name(var), ast_var_value(var));
1911 }
1912
1913 if (!(ast_channel_tech(chan)->properties & AST_CHAN_TP_INTERNAL)
1914 && ast_cdr_serialize_variables(ast_channel_name(chan), &obuf, '=', '\n')) {
1915 ast_str_append(&output, 0, " CDR Variables:\n%s\n", ast_str_buffer(obuf));
1916 }
1917
1918 ast_str_append(&output, 0, " -- Streams --\n");
1919 for (stream_num = 0; stream_num < ast_stream_topology_get_count(ast_channel_get_stream_topology(chan)); stream_num++) {
1920 struct ast_stream *stream = ast_stream_topology_get_stream(ast_channel_get_stream_topology(chan), stream_num);
1921 struct ast_variable *metadata = ast_stream_get_metadata_list(stream);
1922
1923 ast_str_append(&output, 0,
1924 "Name: %s\n"
1925 " Type: %s\n"
1926 " State: %s\n"
1927 " Group: %d\n"
1928 " Formats: %s\n"
1929 " Metadata:\n",
1930 ast_stream_get_name(stream),
1931 ast_codec_media_type2str(ast_stream_get_type(stream)),
1932 ast_stream_state2str(ast_stream_get_state(stream)),
1933 ast_stream_get_group(stream),
1934 ast_format_cap_get_names(ast_stream_get_formats(stream), &codec_buf)
1935 );
1936
1937 if (metadata) {
1938 struct ast_variable *v;
1939 for(v = metadata; v; v = v->next) {
1940 ast_str_append(&output, 0, " %s: %s\n", v->name, v->value);
1941 }
1942 ast_variables_destroy(metadata);
1943 }
1944 }
1945
1946 ast_channel_unlock(chan);
1947
1948 ast_cli(a->fd, "%s", ast_str_buffer(output));
1949 ast_free(output);
1950
1951 ao2_cleanup(bridge);
1952 ast_channel_unref(chan);
1953
1954 return CLI_SUCCESS;
1955 }
1956
1957 /*
1958 * helper function to generate CLI matches from a fixed set of values.
1959 * A NULL word is acceptable.
1960 */
1961 char *ast_cli_complete(const char *word, const char * const choices[], int state)
1962 {
1963 int i, which = 0, len;
1964 len = ast_strlen_zero(word) ? 0 : strlen(word);
1965
1966 for (i = 0; choices[i]; i++) {
1967 if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state) {
1968 if (state != -1) {
1969 return ast_strdup(choices[i]);
1970 }
1971
1972 if (ast_cli_completion_add(ast_strdup(choices[i]))) {
1973 return NULL;
1974 }
1975 }
1976 }
1977 return NULL;
1978 }
1979
1980 char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
1981 {
1982 int wordlen = strlen(word), which = 0;
1983 struct ao2_container *cached_channels;
1984 char *ret = NULL;
1985 struct ao2_iterator iter;
1986 struct ast_channel_snapshot *snapshot;
1987
1988 if (pos != rpos) {
1989 return NULL;
1990 }
1991
1992 cached_channels = ast_channel_cache_all();
1993
1994 iter = ao2_iterator_init(cached_channels, 0);
1995 for (; (snapshot = ao2_iterator_next(&iter)); ao2_ref(snapshot, -1)) {
1996 if (!strncasecmp(word, snapshot->base->name, wordlen) && (++which > state)) {
1997 if (state != -1) {
1998 ret = ast_strdup(snapshot->base->name);
1999 ao2_ref(snapshot, -1);
2000 break;
2001 }
2002
2003 if (ast_cli_completion_add(ast_strdup(snapshot->base->name))) {
2004 ao2_ref(snapshot, -1);
2005 break;
2006 }
2007 }
2008 }
2009 ao2_iterator_destroy(&iter);
2010 ao2_ref(cached_channels, -1);
2011
2012 return ret;
2013 }
2014
2015 static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2016 {
2017 #define FORMAT_STRING "%-25s %-20s %-20s\n"
2018
2019 struct ast_group_info *gi = NULL;
2020 int numchans = 0;
2021 regex_t regexbuf;
2022 int havepattern = 0;
2023
2024 switch (cmd) {
2025 case CLI_INIT:
2026 e->command = "group show channels";
2027 e->usage =
2028 "Usage: group show channels [pattern]\n"
2029 " Lists all currently active channels with channel group(s) specified.\n"
2030 " Optional regular expression pattern is matched to group names for each\n"
2031 " channel.\n";
2032 return NULL;
2033 case CLI_GENERATE:
2034 return NULL;
2035 }
2036
2037 if (a->argc < 3 || a->argc > 4)
2038 return CLI_SHOWUSAGE;
2039
2040 if (a->argc == 4) {
2041 if (regcomp(&regexbuf, a->argv[3], REG_EXTENDED | REG_NOSUB))
2042 return CLI_SHOWUSAGE;
2043 havepattern = 1;
2044 }
2045
2046 ast_cli(a->fd, FORMAT_STRING, "Channel", "Group", "Category");
2047
2048 ast_app_group_list_rdlock();
2049
2050 gi = ast_app_group_list_head();
2051 while (gi) {
2052 if (!havepattern || !regexec(&regexbuf, gi->group, 0, NULL, 0)) {
2053 ast_cli(a->fd, FORMAT_STRING, ast_channel_name(gi->chan), gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category));
2054 numchans++;
2055 }
2056 gi = AST_LIST_NEXT(gi, group_list);
2057 }
2058
2059 ast_app_group_list_unlock();
2060
2061 if (havepattern)
2062 regfree(&regexbuf);
2063
2064 ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
2065 return CLI_SUCCESS;
2066 #undef FORMAT_STRING
2067 }
2068
2069 static char *handle_cli_wait_fullybooted(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2070 {
2071 switch (cmd) {
2072 case CLI_INIT:
2073 e->command = "core waitfullybooted";
2074 e->usage =
2075 "Usage: core waitfullybooted\n"
2076 " Wait until Asterisk has fully booted.\n";
2077 return NULL;
2078 case CLI_GENERATE:
2079 return NULL;
2080 }
2081
2082 while (!ast_fully_booted) {
2083 usleep(100);
2084 }
2085
2086 ast_cli(a->fd, "Asterisk has fully booted.\n");
2087
2088 return CLI_SUCCESS;
2089 }
2090
2091
2092 #ifdef HAVE_MALLOC_TRIM
2093
2094 /*!
2095 * \internal
2096 * \brief Attempt to reclaim unused heap memory.
2097 *
2098 * Users have reported that asterisk will sometimes be killed because it can't allocate
2099 * more than around 3G of memory on a 32 bit system.
2100 *
2101 * Using malloc_trim() will help us to determine if it's because there's a leak or because
2102 * the heap is so fragmented that there isn't enough contiguous memory available.
2103 *
2104 * \note malloc_trim() is a GNU extension and is therefore not portable.
2105 */
2106 static char *handle_cli_malloc_trim(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2107 {
2108 extern int malloc_trim(size_t __pad) __THROW;
2109
2110 switch (cmd) {
2111 case CLI_INIT:
2112 e->command = "malloc trim";
2113 e->usage =
2114 "Usage: malloc trim\n"
2115 " Try to give excess memory back to the OS.\n";
2116 return NULL;
2117 case CLI_GENERATE:
2118 return NULL;
2119 }
2120
2121 if (malloc_trim(0)) {
2122 ast_cli(a->fd, "Returned some memory to the OS.\n");
2123 } else {
2124 ast_cli(a->fd, "No memory returned to the OS.\n");
2125 }
2126
2127 return CLI_SUCCESS;
2128 }
2129
2130 #endif
2131
2132 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
2133
2134 static struct ast_cli_entry cli_cli[] = {
2135 AST_CLI_DEFINE(handle_commandmatchesarray, "Returns command matches array"),
2136
2137 AST_CLI_DEFINE(handle_debug_category, "Enable/disable debugging categories"),
2138
2139 AST_CLI_DEFINE(handle_debug, "Set level of debug chattiness"),
2140 AST_CLI_DEFINE(handle_trace, "Set level of trace chattiness"),
2141 AST_CLI_DEFINE(handle_verbose, "Set level of verbose chattiness"),
2142
2143 AST_CLI_DEFINE(handle_help, "Display help list, or specific help on a command"),
2144 AST_CLI_DEFINE(handle_logger_mute, "Toggle logging output to a console"),
2145
2146 AST_CLI_DEFINE(handle_modlist, "List modules and info"),
2147 AST_CLI_DEFINE(handle_load, "Load a module by name"),
2148 AST_CLI_DEFINE(handle_reload, "Reload configuration for a module"),
2149 AST_CLI_DEFINE(handle_core_reload, "Global reload"),
2150 AST_CLI_DEFINE(handle_unload, "Unload a module by name"),
2151 AST_CLI_DEFINE(handle_refresh, "Completely unloads and loads a module by name"),
2152
2153 AST_CLI_DEFINE(handle_showuptime, "Show uptime information"),
2154
2155 AST_CLI_DEFINE(handle_cli_reload_permissions, "Reload CLI permissions config"),
2156 AST_CLI_DEFINE(handle_cli_show_permissions, "Show CLI permissions"),
2157 AST_CLI_DEFINE(handle_cli_check_permissions, "Try a permissions config for a user"),
2158 AST_CLI_DEFINE(handle_cli_wait_fullybooted, "Wait for Asterisk to be fully booted"),
2159
2160 #ifdef HAVE_MALLOC_TRIM
2161 AST_CLI_DEFINE(handle_cli_malloc_trim, "Return excess memory to the OS"),
2162 #endif
2163
2164 };
2165
2166 static struct ast_cli_entry cli_channels_cli[] = {
2167 AST_CLI_DEFINE(handle_nodebugchan_deprecated, "Disable debugging on channel(s)"),
2168 AST_CLI_DEFINE(handle_chanlist, "Display information on channels"),
2169 AST_CLI_DEFINE(handle_showcalls, "Display information on calls"),
2170 AST_CLI_DEFINE(handle_showchan, "Display information on a specific channel"),
2171 AST_CLI_DEFINE(handle_core_set_debug_channel, "Enable/disable debugging on a channel"),
2172 AST_CLI_DEFINE(group_show_channels, "Display active channels with group(s)"),
2173 AST_CLI_DEFINE(handle_softhangup, "Request a hangup on a given channel"),
2174 };
2175
2176 /*!
2177 * Some regexp characters in cli arguments are reserved and used as separators.
2178 */
2179 static const char cli_rsvd[] = "[]{}|*%";
2180
2181 /*!
2182 * initialize the _full_cmd string and related parameters,
2183 * return 0 on success, -1 on error.
2184 */
2185 static int set_full_cmd(struct ast_cli_entry *e)
2186 {
2187 int i;
2188 char buf[80];
2189
2190 ast_join(buf, sizeof(buf), e->cmda);
2191 e->_full_cmd = ast_strdup(buf);
2192 if (!e->_full_cmd) {
2193 ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
2194 return -1;
2195 }
2196 e->cmdlen = strcspn(e->_full_cmd, cli_rsvd);
2197 for (i = 0; e->cmda[i]; i++)
2198 ;
2199 e->args = i;
2200 return 0;
2201 }
2202
2203 /*! \brief cleanup (free) cli_perms linkedlist. */
2204 static void destroy_user_perms(void)
2205 {
2206 struct cli_perm *perm;
2207 struct usergroup_cli_perm *user_perm;
2208
2209 AST_RWLIST_WRLOCK(&cli_perms);
2210 while ((user_perm = AST_LIST_REMOVE_HEAD(&cli_perms, list))) {
2211 while ((perm = AST_LIST_REMOVE_HEAD(user_perm->perms, list))) {
2212 ast_free(perm->command);
2213 ast_free(perm);
2214 }
2215 ast_free(user_perm);
2216 }
2217 AST_RWLIST_UNLOCK(&cli_perms);
2218 }
2219
2220 int ast_cli_perms_init(int reload)
2221 {
2222 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2223 struct ast_config *cfg;
2224 char *cat = NULL;
2225 struct ast_variable *v;
2226 struct usergroup_cli_perm *user_group, *cp_entry;
2227 struct cli_perm *perm = NULL;
2228 struct passwd *pw;
2229 struct group *gr;
2230
2231 if (ast_mutex_trylock(&permsconfiglock)) {
2232 ast_log(LOG_NOTICE, "You must wait until last 'cli reload permissions' command finish\n");
2233 return 1;
2234 }
2235
2236 cfg = ast_config_load2(perms_config, "" /* core, can't reload */, config_flags);
2237 if (!cfg) {
2238 ast_mutex_unlock(&permsconfiglock);
2239 return 1;
2240 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
2241 ast_mutex_unlock(&permsconfiglock);
2242 return 0;
2243 }
2244
2245 /* free current structures. */
2246 destroy_user_perms();
2247
2248 while ((cat = ast_category_browse(cfg, cat))) {
2249 if (!strcasecmp(cat, "general")) {
2250 /* General options */
2251 for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
2252 if (!strcasecmp(v->name, "default_perm")) {
2253 cli_default_perm = (!strcasecmp(v->value, "permit")) ? 1: 0;
2254 }
2255 }
2256 continue;
2257 }
2258
2259 /* users or groups */
2260 gr = NULL, pw = NULL;
2261 if (cat[0] == '@') {
2262 /* This is a group */
2263 gr = getgrnam(&cat[1]);
2264 if (!gr) {
2265 ast_log (LOG_WARNING, "Unknown group '%s'\n", &cat[1]);
2266 continue;
2267 }
2268 } else {
2269 /* This is a user */
2270 pw = getpwnam(cat);
2271 if (!pw) {
2272 ast_log (LOG_WARNING, "Unknown user '%s'\n", cat);
2273 continue;
2274 }
2275 }
2276 user_group = NULL;
2277 /* Check for duplicates */
2278 AST_RWLIST_WRLOCK(&cli_perms);
2279 AST_LIST_TRAVERSE(&cli_perms, cp_entry, list) {
2280 if ((pw && cp_entry->uid == pw->pw_uid) || (gr && cp_entry->gid == gr->gr_gid)) {
2281 /* if it is duplicated, just added this new settings, to
2282 the current list. */
2283 user_group = cp_entry;
2284 break;
2285 }
2286 }
2287 AST_RWLIST_UNLOCK(&cli_perms);
2288
2289 if (!user_group) {
2290 /* alloc space for the new user config. */
2291 user_group = ast_calloc(1, sizeof(*user_group));
2292 if (!user_group) {
2293 continue;
2294 }
2295 user_group->uid = (pw ? pw->pw_uid : -1);
2296 user_group->gid = (gr ? gr->gr_gid : -1);
2297 user_group->perms = ast_calloc(1, sizeof(*user_group->perms));
2298 if (!user_group->perms) {
2299 ast_free(user_group);
2300 continue;
2301 }
2302 }
2303 for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
2304 if (ast_strlen_zero(v->value)) {
2305 /* we need to check this condition cause it could break security. */
2306 ast_log(LOG_WARNING, "Empty permit/deny option in user '%s'\n", cat);
2307 continue;
2308 }
2309 if (!strcasecmp(v->name, "permit")) {
2310 perm = ast_calloc(1, sizeof(*perm));
2311 if (perm) {
2312 perm->permit = 1;
2313 perm->command = ast_strdup(v->value);
2314 }
2315 } else if (!strcasecmp(v->name, "deny")) {
2316 perm = ast_calloc(1, sizeof(*perm));
2317 if (perm) {
2318 perm->permit = 0;
2319 perm->command = ast_strdup(v->value);
2320 }
2321 } else {
2322 /* up to now, only 'permit' and 'deny' are possible values. */
2323 ast_log(LOG_WARNING, "Unknown '%s' option\n", v->name);
2324 continue;
2325 }
2326 if (perm) {
2327 /* Added the permission to the user's list. */
2328 AST_LIST_INSERT_TAIL(user_group->perms, perm, list);
2329 perm = NULL;
2330 }
2331 }
2332 AST_RWLIST_WRLOCK(&cli_perms);
2333 AST_RWLIST_INSERT_TAIL(&cli_perms, user_group, list);
2334 AST_RWLIST_UNLOCK(&cli_perms);
2335 }
2336
2337 ast_config_destroy(cfg);
2338 ast_mutex_unlock(&permsconfiglock);
2339 return 0;
2340 }
2341
2342 static void cli_shutdown(void)
2343 {
2344 ast_cli_unregister_multiple(cli_cli, ARRAY_LEN(cli_cli));
2345 }
2346
2347 static void cli_channels_shutdown(void)
2348 {
2349 ast_cli_unregister_multiple(cli_channels_cli, ARRAY_LEN(cli_channels_cli));
2350 }
2351
2352 /*! \brief initialize the _full_cmd string in * each of the builtins. */
2353 void ast_builtins_init(void)
2354 {
2355 AST_VECTOR_INIT(&shutdown_commands, 0);
2356 ast_cli_register_multiple(cli_cli, ARRAY_LEN(cli_cli));
2357 ast_register_cleanup(cli_shutdown);
2358 }
2359
2360 void ast_cli_channels_init(void)
2361 {
2362 ast_cli_register_multiple(cli_channels_cli, ARRAY_LEN(cli_channels_cli));
2363 ast_register_cleanup(cli_channels_shutdown);
2364 }
2365
2366 /*!
2367 * match a word in the CLI entry.
2368 * returns -1 on mismatch, 0 on match of an optional word,
2369 * 1 on match of a full word.
2370 *
2371 * The pattern can be
2372 * any_word match for equal
2373 * [foo|bar|baz] optionally, one of these words
2374 * {foo|bar|baz} exactly, one of these words
2375 * % any word
2376 */
2377 static int word_match(const char *cmd, const char *cli_word)
2378 {
2379 int l;
2380 char *pos;
2381
2382 if (ast_strlen_zero(cmd) || ast_strlen_zero(cli_word))
2383 return -1;
2384 if (!strchr(cli_rsvd, cli_word[0])) /* normal match */
2385 return (strcasecmp(cmd, cli_word) == 0) ? 1 : -1;
2386 l = strlen(cmd);
2387 /* wildcard match - will extend in the future */
2388 if (l > 0 && cli_word[0] == '%') {
2389 return 1; /* wildcard */
2390 }
2391
2392 /* Start a search for the command entered against the cli word in question */
2393 pos = strcasestr(cli_word, cmd);
2394 while (pos) {
2395
2396 /*
2397 *Check if the word matched with is surrounded by reserved characters on both sides
2398 * and isn't at the beginning of the cli_word since that would make it check in a location we shouldn't know about.
2399 * If it is surrounded by reserved chars and isn't at the beginning, it's a match.
2400 */
2401 if (pos != cli_word && strchr(cli_rsvd, pos[-1]) && strchr(cli_rsvd, pos[l])) {
2402 return 1; /* valid match */
2403 }
2404
2405 /* Ok, that one didn't match, strcasestr to the next appearance of the command and start over.*/
2406 pos = strcasestr(pos + 1, cmd);
2407 }
2408 /* If no matches were found over the course of the while loop, we hit the end of the string. It's a mismatch. */
2409 return -1;
2410 }
2411
2412 /*! \brief if word is a valid prefix for token, returns the pos-th
2413 * match as a malloced string, or NULL otherwise.
2414 * Always tell in *actual how many matches we got.
2415 */
2416 static char *is_prefix(const char *word, const char *token,
2417 int pos, int *actual)
2418 {
2419 int lw;
2420 char *s, *t1;
2421
2422 *actual = 0;
2423 if (ast_strlen_zero(token))
2424 return NULL;
2425 if (ast_strlen_zero(word))
2426 word = ""; /* dummy */
2427 lw = strlen(word);
2428 if (strcspn(word, cli_rsvd) != lw)
2429 return NULL; /* no match if word has reserved chars */
2430 if (strchr(cli_rsvd, token[0]) == NULL) { /* regular match */
2431 if (strncasecmp(token, word, lw)) /* no match */
2432 return NULL;
2433 *actual = 1;
2434 return (pos != 0) ? NULL : ast_strdup(token);
2435 }
2436 /* now handle regexp match */
2437
2438 /* Wildcard always matches, so we never do is_prefix on them */
2439
2440 t1 = ast_strdupa(token + 1); /* copy, skipping first char */
2441 while (pos >= 0 && (s = strsep(&t1, cli_rsvd)) && *s) {
2442 if (*s == '%') /* wildcard */
2443 continue;
2444 if (strncasecmp(s, word, lw)) /* no match */
2445 continue;
2446 (*actual)++;
2447 if (pos-- == 0)
2448 return ast_strdup(s);
2449 }
2450 return NULL;
2451 }
2452
2453 /*!
2454 * \internal
2455 * \brief locate a cli command in the 'helpers' list (which must be locked).
2456 * The search compares word by word taking care of regexps in e->cmda
2457 * This function will return NULL when nothing is matched, or the ast_cli_entry that matched.
2458 * \param cmds
2459 * \param match_type has 3 possible values:
2460 * 0 returns if the search key is equal or longer than the entry.
2461 * note that trailing optional arguments are skipped.
2462 * -1 true if the mismatch is on the last word XXX not true!
2463 * 1 true only on complete, exact match.
2464 *
2465 */
2466 static struct ast_cli_entry *find_cli(const char * const cmds[], int match_type)
2467 {
2468 int matchlen = -1; /* length of longest match so far */
2469 struct ast_cli_entry *cand = NULL, *e=NULL;
2470
2471 while ( (e = cli_next(e)) ) {
2472 /* word-by word regexp comparison */
2473 const char * const *src = cmds;
2474 const char * const *dst = e->cmda;
2475 int n = 0;
2476 for (;; dst++, src += n) {
2477 n = word_match(*src, *dst);
2478 if (n < 0)
2479 break;
2480 }
2481 if (ast_strlen_zero(*dst) || ((*dst)[0] == '[' && ast_strlen_zero(dst[1]))) {
2482 /* no more words in 'e' */
2483 if (ast_strlen_zero(*src)) /* exact match, cannot do better */
2484 break;
2485 /* Here, cmds has more words than the entry 'e' */
2486 if (match_type != 0) /* but we look for almost exact match... */
2487 continue; /* so we skip this one. */
2488 /* otherwise we like it (case 0) */
2489 } else { /* still words in 'e' */
2490 if (ast_strlen_zero(*src))
2491 continue; /* cmds is shorter than 'e', not good */
2492 /* Here we have leftover words in cmds and 'e',
2493 * but there is a mismatch. We only accept this one if match_type == -1
2494 * and this is the last word for both.
2495 */
2496 if (match_type != -1 || !ast_strlen_zero(src[1]) ||
2497 !ast_strlen_zero(dst[1])) /* not the one we look for */
2498 continue;
2499 /* good, we are in case match_type == -1 and mismatch on last word */
2500 }
2501 if (src - cmds > matchlen) { /* remember the candidate */
2502 matchlen = src - cmds;
2503 cand = e;
2504 }
2505 }
2506
2507 return e ? e : cand;
2508 }
2509
2510 static char *find_best(const char *argv[])
2511 {
2512 static char cmdline[80];
2513 int x;
2514 /* See how close we get, then print the candidate */
2515 const char *myargv[AST_MAX_CMD_LEN] = { NULL, };
2516
2517 AST_RWLIST_RDLOCK(&helpers);
2518 for (x = 0; argv[x]; x++) {
2519 myargv[x] = argv[x];
2520 if (!find_cli(myargv, -1))
2521 break;
2522 }
2523 AST_RWLIST_UNLOCK(&helpers);
2524 ast_join(cmdline, sizeof(cmdline), myargv);
2525 return cmdline;
2526 }
2527
2528 static int cli_is_registered(struct ast_cli_entry *e)
2529 {
2530 struct ast_cli_entry *cur = NULL;
2531
2532 while ((cur = cli_next(cur))) {
2533 if (cur == e) {
2534 return 1;
2535 }
2536 }
2537 return 0;
2538 }
2539
2540 static void remove_shutdown_command(struct ast_cli_entry *e)
2541 {
2542 ast_rwlock_wrlock(&shutdown_commands_lock);
2543 AST_VECTOR_REMOVE_ELEM_UNORDERED(&shutdown_commands, e, AST_VECTOR_ELEM_CLEANUP_NOOP);
2544 ast_rwlock_unlock(&shutdown_commands_lock);
2545 }
2546
2547 int ast_cli_unregister(struct ast_cli_entry *e)
2548 {
2549 if (e->inuse) {
2550 ast_log(LOG_WARNING, "Can't remove command that is in use\n");
2551 } else {
2552 AST_RWLIST_WRLOCK(&helpers);
2553 AST_RWLIST_REMOVE(&helpers, e, list);
2554 AST_RWLIST_UNLOCK(&helpers);
2555 remove_shutdown_command(e);
2556 ast_free(e->_full_cmd);
2557 e->_full_cmd = NULL;
2558 if (e->handler) {
2559 /* this is a new-style entry. Reset fields and free memory. */
2560 char *cmda = (char *) e->cmda;
2561 memset(cmda, '\0', sizeof(e->cmda));
2562 ast_free(e->command);
2563 e->command = NULL;
2564 e->usage = NULL;
2565 }
2566 }
2567 return 0;
2568 }
2569
2570 int __ast_cli_register(struct ast_cli_entry *e, struct ast_module *module)
2571 {
2572 struct ast_cli_entry *cur;
2573 int i, lf, ret = -1;
2574
2575 struct ast_cli_args a; /* fake argument */
2576 char **dst = (char **)e->cmda; /* need to cast as the entry is readonly */
2577 char *s;
2578
2579 AST_RWLIST_WRLOCK(&helpers);
2580
2581 if (cli_is_registered(e)) {
2582 ast_log(LOG_WARNING, "Command '%s' already registered (the same ast_cli_entry)\n",
2583 S_OR(e->_full_cmd, e->command));
2584 ret = 0; /* report success */
2585 goto done;
2586 }
2587
2588 memset(&a, '\0', sizeof(a));
2589
2590 e->module = module;
2591 /* No module reference needed here, the module called us. */
2592 e->handler(e, CLI_INIT, &a);
2593
2594 /* XXX check that usage and command are filled up */
2595 s = ast_skip_blanks(e->command);
2596 s = e->command = ast_strdup(s);
2597 for (i=0; !ast_strlen_zero(s) && i < AST_MAX_CMD_LEN-1; i++) {
2598 *dst++ = s; /* store string */
2599 s = ast_skip_nonblanks(s);
2600 if (*s == '\0') /* we are done */
2601 break;
2602 *s++ = '\0';
2603 s = ast_skip_blanks(s);
2604 }
2605 *dst++ = NULL;
2606
2607 if (find_cli(e->cmda, 1)) {
2608 ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n",
2609 S_OR(e->_full_cmd, e->command));
2610 goto done;
2611 }
2612 if (set_full_cmd(e)) {
2613 ast_log(LOG_WARNING, "Error registering CLI Command '%s'\n",
2614 S_OR(e->_full_cmd, e->command));
2615 goto done;
2616 }
2617
2618 lf = e->cmdlen;
2619 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
2620 int len = cur->cmdlen;
2621 if (lf < len)
2622 len = lf;
2623 if (strncasecmp(e->_full_cmd, cur->_full_cmd, len) < 0) {
2624 AST_RWLIST_INSERT_BEFORE_CURRENT(e, list);
2625 break;
2626 }
2627 }
2628 AST_RWLIST_TRAVERSE_SAFE_END;
2629
2630 if (!cur)
2631 AST_RWLIST_INSERT_TAIL(&helpers, e, list);
2632 ret = 0; /* success */
2633
2634 done:
2635 AST_RWLIST_UNLOCK(&helpers);
2636 if (ret) {
2637 ast_free(e->command);
2638 e->command = NULL;
2639 }
2640
2641 return ret;
2642 }
2643
2644 /*
2645 * register/unregister an array of entries.
2646 */
2647 int __ast_cli_register_multiple(struct ast_cli_entry *e, int len, struct ast_module *module)
2648 {
2649 int i, res = 0;
2650
2651 for (i = 0; i < len; i++) {
2652 res |= __ast_cli_register(e + i, module);
2653 }
2654
2655 return res;
2656 }
2657
2658 int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
2659 {
2660 int i, res = 0;
2661
2662 for (i = 0; i < len; i++)
2663 res |= ast_cli_unregister(e + i);
2664
2665 return res;
2666 }
2667
2668
2669 /*! \brief helper for final part of handle_help
2670 * if locked = 1, assume the list is already locked
2671 */
2672 static char *help1(int fd, const char * const match[], int locked)
2673 {
2674 char matchstr[80] = "";
2675 struct ast_cli_entry *e = NULL;
2676 int len = 0;
2677 int found = 0;
2678
2679 if (match) {
2680 ast_join(matchstr, sizeof(matchstr), match);
2681 len = strlen(matchstr);
2682 }
2683 if (!locked)
2684 AST_RWLIST_RDLOCK(&helpers);
2685 while ( (e = cli_next(e)) ) {
2686 /* Hide commands that start with '_' */
2687 if (e->_full_cmd[0] == '_')
2688 continue;
2689 if (match && strncasecmp(matchstr, e->_full_cmd, len))
2690 continue;
2691 ast_cli(fd, "%-30s -- %s\n", e->_full_cmd,
2692 S_OR(e->summary, "<no description available>"));
2693 found++;
2694 }
2695 if (!locked)
2696 AST_RWLIST_UNLOCK(&helpers);
2697 if (!found && matchstr[0])
2698 ast_cli(fd, "No such command '%s'.\n", matchstr);
2699 return CLI_SUCCESS;
2700 }
2701
2702 static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2703 {
2704 char fullcmd[80];
2705 struct ast_cli_entry *my_e;
2706 char *res = CLI_SUCCESS;
2707
2708 if (cmd == CLI_INIT) {
2709 e->command = "core show help";
2710 e->usage =
2711 "Usage: core show help [topic]\n"
2712 " When called with a topic as an argument, displays usage\n"
2713 " information on the given command. If called without a\n"
2714 " topic, it provides a list of commands.\n";
2715 return NULL;
2716
2717 } else if (cmd == CLI_GENERATE) {
2718 /* skip first 14 or 15 chars, "core show help " */
2719 int l = strlen(a->line);
2720
2721 if (l > 15) {
2722 l = 15;
2723 }
2724 /* XXX watch out, should stop to the non-generator parts */
2725 return __ast_cli_generator(a->line + l, a->word, a->n, 0);
2726 }
2727 if (a->argc == e->args) {
2728 return help1(a->fd, NULL, 0);
2729 }
2730
2731 AST_RWLIST_RDLOCK(&helpers);
2732 my_e = find_cli(a->argv + 3, 1); /* try exact match first */
2733 if (!my_e) {
2734 res = help1(a->fd, a->argv + 3, 1 /* locked */);
2735 AST_RWLIST_UNLOCK(&helpers);
2736 return res;
2737 }
2738 if (my_e->usage)
2739 ast_cli(a->fd, "%s", my_e->usage);
2740 else {
2741 ast_join(fullcmd, sizeof(fullcmd), a->argv + 3);
2742 ast_cli(a->fd, "No help text available for '%s'.\n", fullcmd);
2743 }
2744 AST_RWLIST_UNLOCK(&helpers);
2745 return res;
2746 }
2747
2748 static char *parse_args(const char *s, int *argc, const char *argv[], int max, int *trailingwhitespace)
2749 {
2750 char *duplicate, *cur;
2751 int x = 0;
2752 int quoted = 0;
2753 int escaped = 0;
2754 int whitespace = 1;
2755 int dummy = 0;
2756
2757 if (trailingwhitespace == NULL)
2758 trailingwhitespace = &dummy;
2759 *trailingwhitespace = 0;
2760 if (s == NULL) /* invalid, though! */
2761 return NULL;
2762 /* make a copy to store the parsed string */
2763 if (!(duplicate = ast_strdup(s)))
2764 return NULL;
2765
2766 cur = duplicate;
2767
2768 /* Remove leading spaces from the command */
2769 while (isspace(*s)) {
2770 cur++;
2771 s++;
2772 }
2773
2774 /* scan the original string copying into cur when needed */
2775 for (; *s ; s++) {
2776 if (x >= max - 1) {
2777 ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
2778 break;
2779 }
2780 if (*s == '"' && !escaped) {
2781 quoted = !quoted;
2782 if (quoted && whitespace) {
2783 /* start a quoted string from previous whitespace: new argument */
2784 argv[x++] = cur;
2785 whitespace = 0;
2786 }
2787 } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
2788 /* If we are not already in whitespace, and not in a quoted string or
2789 processing an escape sequence, and just entered whitespace, then
2790 finalize the previous argument and remember that we are in whitespace
2791 */
2792 if (!whitespace) {
2793 *cur++ = '\0';
2794 whitespace = 1;
2795 }
2796 } else if (*s == '\\' && !escaped) {
2797 escaped = 1;
2798 } else {
2799 if (whitespace) {
2800 /* we leave whitespace, and are not quoted. So it's a new argument */
2801 argv[x++] = cur;
2802 whitespace = 0;
2803 }
2804 *cur++ = *s;
2805 escaped = 0;
2806 }
2807 }
2808 /* Null terminate */
2809 *cur++ = '\0';
2810 /* XXX put a NULL in the last argument, because some functions that take
2811 * the array may want a null-terminated array.
2812 * argc still reflects the number of non-NULL entries.
2813 */
2814 argv[x] = NULL;
2815 *argc = x;
2816 *trailingwhitespace = whitespace;
2817 return duplicate;
2818 }
2819
2820 char **ast_cli_completion_matches(const char *text, const char *word)
2821 {
2822 struct ast_vector_string *vec = ast_cli_completion_vector(text, word);
2823 char **match_list;
2824
2825 if (!vec) {
2826 return NULL;
2827 }
2828
2829 if (AST_VECTOR_APPEND(vec, NULL)) {
2830 /* We failed to NULL terminate the elements */
2831 AST_VECTOR_CALLBACK_VOID(vec, ast_free);
2832 AST_VECTOR_PTR_FREE(vec);
2833
2834 return NULL;
2835 }
2836
2837 match_list = AST_VECTOR_STEAL_ELEMENTS(vec);
2838 AST_VECTOR_PTR_FREE(vec);
2839
2840 return match_list;
2841 }
2842
2843 AST_THREADSTORAGE_RAW(completion_storage);
2844
2845 /*!
2846 * \internal
2847 * \brief Add a value to the vector.
2848 *
2849 * \param vec Vector to add \a value to. Must be from threadstorage.
2850 * \param value The value to add.
2851 *
2852 * \retval 0 Success
2853 * \retval -1 Failure
2854 */
2855 static int cli_completion_vector_add(struct ast_vector_string *vec, char *value)
2856 {
2857 if (!value) {
2858 return 0;
2859 }
2860
2861 if (!vec || AST_VECTOR_ADD_SORTED(vec, value, strcasecmp)) {
2862 if (vec) {
2863 ast_threadstorage_set_ptr(&completion_storage, NULL);
2864
2865 AST_VECTOR_CALLBACK_VOID(vec, ast_free);
2866 AST_VECTOR_FREE(vec);
2867 }
2868 ast_free(value);
2869
2870 return -1;
2871 }
2872
2873 return 0;
2874 }
2875
2876 int ast_cli_completion_add(char *value)
2877 {
2878 return cli_completion_vector_add(ast_threadstorage_get_ptr(&completion_storage), value);
2879 }
2880
2881 struct ast_vector_string *ast_cli_completion_vector(const char *text, const char *word)
2882 {
2883 char *retstr, *prevstr;
2884 size_t max_equal;
2885 size_t which = 0;
2886 struct ast_vector_string *vec = ast_calloc(1, sizeof(*vec));
2887
2888 /* Recursion into this function is a coding error. */
2889 ast_assert(!ast_threadstorage_get_ptr(&completion_storage));
2890
2891 if (!vec) {
2892 return NULL;
2893 }
2894
2895 if (ast_threadstorage_set_ptr(&completion_storage, vec)) {
2896 ast_log(LOG_ERROR, "Failed to initialize threadstorage for completion.\n");
2897 ast_free(vec);
2898
2899 return NULL;
2900 }
2901
2902 while ((retstr = ast_cli_generator(text, word, which)) != NULL) {
2903 if (cli_completion_vector_add(vec, retstr)) {
2904 ast_threadstorage_set_ptr(&completion_storage, NULL);
2905
2906 goto vector_cleanup;
2907 }
2908
2909 ++which;
2910 }
2911
2912 ast_threadstorage_set_ptr(&completion_storage, NULL);
2913
2914 if (!AST_VECTOR_SIZE(vec)) {
2915 AST_VECTOR_PTR_FREE(vec);
2916
2917 return NULL;
2918 }
2919
2920 prevstr = AST_VECTOR_GET(vec, 0);
2921 max_equal = strlen(prevstr);
2922 which = 1;
2923
2924 /* Find the longest substring that is common to all results
2925 * (it is a candidate for completion), and store a copy in entry 0.
2926 */
2927 while (which < AST_VECTOR_SIZE(vec)) {
2928 size_t i = 0;
2929
2930 retstr = AST_VECTOR_GET(vec, which);
2931 /* Check for and remove duplicate strings. */
2932 if (!strcasecmp(prevstr, retstr)) {
2933 AST_VECTOR_REMOVE(vec, which, 1);
2934 ast_free(retstr);
2935
2936 continue;
2937 }
2938
2939 while (i < max_equal && toupper(prevstr[i]) == toupper(retstr[i])) {
2940 i++;
2941 }
2942
2943 max_equal = i;
2944 prevstr = retstr;
2945 ++which;
2946 }
2947
2948 /* Insert longest match to position 0. */
2949 retstr = ast_strndup(AST_VECTOR_GET(vec, 0), max_equal);
2950 if (!retstr || AST_VECTOR_INSERT_AT(vec, 0, retstr)) {
2951 ast_free(retstr);
2952
2953 goto vector_cleanup;
2954 }
2955
2956 return vec;
2957
2958 vector_cleanup:
2959 AST_VECTOR_CALLBACK_VOID(vec, ast_free);
2960 AST_VECTOR_PTR_FREE(vec);
2961
2962 return NULL;
2963 }
2964
2965 /*! \brief returns true if there are more words to match */
2966 static int more_words (const char * const *dst)
2967 {
2968 int i;
2969 for (i = 0; dst[i]; i++) {
2970 if (dst[i][0] != '[')
2971 return -1;
2972 }
2973 return 0;
2974 }
2975
2976 /*
2977 * generate the entry at position 'state'
2978 */
2979 static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
2980 {
2981 const char *argv[AST_MAX_ARGS];
2982 struct ast_cli_entry *e = NULL;
2983 int x = 0, argindex, matchlen;
2984 int matchnum=0;
2985 char *ret = NULL;
2986 char matchstr[80] = "";
2987 int tws = 0;
2988 /* Split the argument into an array of words */
2989 char *duplicate = parse_args(text, &x, argv, ARRAY_LEN(argv), &tws);
2990
2991 if (!duplicate) /* malloc error */
2992 return NULL;
2993
2994 /* Compute the index of the last argument (could be an empty string) */
2995 argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
2996
2997 /* rebuild the command, ignore terminating white space and flatten space */
2998 ast_join(matchstr, sizeof(matchstr)-1, argv);
2999 matchlen = strlen(matchstr);
3000 if (tws) {
3001 strcat(matchstr, " "); /* XXX */
3002 if (matchlen)
3003 matchlen++;
3004 }
3005 if (lock)
3006 AST_RWLIST_RDLOCK(&helpers);
3007 while ( (e = cli_next(e)) ) {
3008 /* XXX repeated code */
3009 int src = 0, dst = 0, n = 0;
3010
3011 if (e->command[0] == '_')
3012 continue;
3013
3014 /*
3015 * Try to match words, up to and excluding the last word, which
3016 * is either a blank or something that we want to extend.
3017 */
3018 for (;src < argindex; dst++, src += n) {
3019 n = word_match(argv[src], e->cmda[dst]);
3020 if (n < 0)
3021 break;
3022 }
3023
3024 if (src != argindex && more_words(e->cmda + dst)) /* not a match */
3025 continue;
3026 ret = is_prefix(argv[src], e->cmda[dst], state - matchnum, &n);
3027 matchnum += n; /* this many matches here */
3028 if (ret) {
3029 /*
3030 * argv[src] is a valid prefix of the next word in this
3031 * command. If this is also the correct entry, return it.
3032 */
3033 if (matchnum > state)
3034 break;
3035 ast_free(ret);
3036 ret = NULL;
3037 } else if (ast_strlen_zero(e->cmda[dst])) {
3038 /*
3039 * This entry is a prefix of the command string entered
3040 * (only one entry in the list should have this property).
3041 * Run the generator if one is available. In any case we are done.
3042 */
3043 if (e->handler) { /* new style command */
3044 struct ast_cli_args a = {
3045 .line = matchstr, .word = word,
3046 .pos = argindex,
3047 .n = state - matchnum,
3048 .argv = argv,
3049 .argc = x};
3050
3051 /* If the command is in a module it must be running. */
3052 if (!e->module || ast_module_running_ref(e->module)) {
3053 ret = e->handler(e, CLI_GENERATE, &a);
3054 ast_module_unref(e->module);
3055 }
3056 }
3057 if (ret)
3058 break;
3059 }
3060 }
3061 if (lock)
3062 AST_RWLIST_UNLOCK(&helpers);
3063 ast_free(duplicate);
3064 return ret;
3065 }
3066
3067 char *ast_cli_generator(const char *text, const char *word, int state)
3068 {
3069 return __ast_cli_generator(text, word, state, 1);
3070 }
3071
3072 static int allowed_on_shutdown(struct ast_cli_entry *e)
3073 {
3074 int found = 0;
3075 int i;
3076
3077 ast_rwlock_rdlock(&shutdown_commands_lock);
3078 for (i = 0; i < AST_VECTOR_SIZE(&shutdown_commands); ++i) {
3079 if (e == AST_VECTOR_GET(&shutdown_commands, i)) {
3080 found = 1;
3081 break;
3082 }
3083 }
3084 ast_rwlock_unlock(&shutdown_commands_lock);
3085
3086 return found;
3087 }
3088
3089 int ast_cli_command_full(int uid, int gid, int fd, const char *s)
3090 {
3091 const char *args[AST_MAX_ARGS + 1];
3092 struct ast_cli_entry *e = NULL;
3093 int x;
3094 char *duplicate = parse_args(s, &x, args + 1, AST_MAX_ARGS, NULL);
3095 char tmp[AST_MAX_ARGS + 1];
3096 char *retval = CLI_FAILURE;
3097 struct ast_cli_args a = {
3098 .fd = fd, .argc = x, .argv = args+1 };
3099
3100 if (duplicate == NULL)
3101 return RESULT_FAILURE;
3102
3103 if (x < 1) /* We need at least one entry, otherwise ignore */
3104 goto done;
3105
3106 AST_RWLIST_RDLOCK(&helpers);
3107 e = find_cli(args + 1, 0);
3108 if (e)
3109 ast_atomic_fetchadd_int(&e->inuse, 1);
3110 AST_RWLIST_UNLOCK(&helpers);
3111 if (e == NULL) {
3112 ast_cli(fd, "No such command '%s' (type 'core show help %s' for other possible commands)\n", s, find_best(args + 1));
3113 goto done;
3114 }
3115
3116 if (ast_shutting_down() && !allowed_on_shutdown(e)) {
3117 ast_cli(fd, "Command '%s' cannot be run during shutdown\n", s);
3118 goto done;
3119 }
3120
3121 ast_join(tmp, sizeof(tmp), args + 1);
3122 /* Check if the user has rights to run this command. */
3123 if (!cli_has_permissions(uid, gid, tmp)) {
3124 ast_cli(fd, "You don't have permissions to run '%s' command\n", tmp);
3125 goto done;
3126 }
3127
3128 /*
3129 * Within the handler, argv[-1] contains a pointer to the ast_cli_entry.
3130 * Remember that the array returned by parse_args is NULL-terminated.
3131 */
3132 args[0] = (char *)e;
3133
3134 /* If the command is in a module it must be running. */
3135 if (!e->module || ast_module_running_ref(e->module)) {
3136 retval = e->handler(e, CLI_HANDLER, &a);
3137 ast_module_unref(e->module);
3138 }
3139
3140 if (retval == CLI_SHOWUSAGE) {
3141 ast_cli(fd, "%s", S_OR(e->usage, "Invalid usage, but no usage information available.\n"));
3142 } else if (retval == CLI_FAILURE) {
3143 ast_cli(fd, "Command '%s' failed.\n", s);
3144 }
3145
3146 done:
3147 if (e) {
3148 ast_atomic_fetchadd_int(&e->inuse, -1);
3149 }
3150 ast_free(duplicate);
3151 return retval == CLI_SUCCESS ? RESULT_SUCCESS : RESULT_FAILURE;
3152 }
3153
3154 int ast_cli_command_multiple_full(int uid, int gid, int fd, size_t size, const char *s)
3155 {
3156 char cmd[512];
3157 int x, y = 0, count = 0;
3158
3159 for (x = 0; x < size; x++) {
3160 cmd[y] = s[x];
3161 y++;
3162 if (s[x] == '\0') {
3163 ast_cli_command_full(uid, gid, fd, cmd);
3164 y = 0;
3165 count++;
3166 }
3167 }
3168 return count;
3169 }
3170
3171 void ast_cli_print_timestr_fromseconds(int fd, int seconds, const char *prefix)
3172 {
3173 print_uptimestr(fd, ast_tv(seconds, 0), prefix, 0);
3174 }
3175
3176 int ast_cli_allow_at_shutdown(struct ast_cli_entry *e)
3177 {
3178 int res;
3179
3180 ast_rwlock_wrlock(&shutdown_commands_lock);
3181 res = AST_VECTOR_APPEND(&shutdown_commands, e);
3182 ast_rwlock_unlock(&shutdown_commands_lock);
3183
3184 return res;
3185 }