cli.c 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Standard Command Line Interface
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. */
  24. /*! \li \ref cli.c uses the configuration file \ref cli_permissions.conf
  25. * \addtogroup configuration_file Configuration Files
  26. */
  27. /*!
  28. * \page cli_permissions.conf cli_permissions.conf
  29. * \verbinclude cli_permissions.conf.sample
  30. */
  31. /*** MODULEINFO
  32. <support_level>core</support_level>
  33. ***/
  34. #include "asterisk.h"
  35. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  36. #include "asterisk/_private.h"
  37. #include "asterisk/paths.h" /* use ast_config_AST_MODULE_DIR */
  38. #include <sys/signal.h>
  39. #include <signal.h>
  40. #include <ctype.h>
  41. #include <regex.h>
  42. #include <pwd.h>
  43. #include <grp.h>
  44. #include <editline/readline.h>
  45. #include "asterisk/cli.h"
  46. #include "asterisk/linkedlists.h"
  47. #include "asterisk/module.h"
  48. #include "asterisk/pbx.h"
  49. #include "asterisk/channel.h"
  50. #include "asterisk/utils.h"
  51. #include "asterisk/app.h"
  52. #include "asterisk/lock.h"
  53. #include "asterisk/threadstorage.h"
  54. #include "asterisk/translate.h"
  55. #include "asterisk/bridge.h"
  56. #include "asterisk/stasis_channels.h"
  57. #include "asterisk/stasis_bridges.h"
  58. /*!
  59. * \brief List of restrictions per user.
  60. */
  61. struct cli_perm {
  62. unsigned int permit:1; /*!< 1=Permit 0=Deny */
  63. char *command; /*!< Command name (to apply restrictions) */
  64. AST_LIST_ENTRY(cli_perm) list;
  65. };
  66. AST_LIST_HEAD_NOLOCK(cli_perm_head, cli_perm);
  67. /*! \brief list of users to apply restrictions. */
  68. struct usergroup_cli_perm {
  69. int uid; /*!< User ID (-1 disabled) */
  70. int gid; /*!< Group ID (-1 disabled) */
  71. struct cli_perm_head *perms; /*!< List of permissions. */
  72. AST_LIST_ENTRY(usergroup_cli_perm) list;/*!< List mechanics */
  73. };
  74. /*! \brief CLI permissions config file. */
  75. static const char perms_config[] = "cli_permissions.conf";
  76. /*! \brief Default permissions value 1=Permit 0=Deny */
  77. static int cli_default_perm = 1;
  78. /*! \brief mutex used to prevent a user from running the 'cli reload permissions' command while
  79. * it is already running. */
  80. AST_MUTEX_DEFINE_STATIC(permsconfiglock);
  81. /*! \brief List of users and permissions. */
  82. static AST_RWLIST_HEAD_STATIC(cli_perms, usergroup_cli_perm);
  83. /*!
  84. * \brief map a debug or verbose level to a module name
  85. */
  86. struct module_level {
  87. unsigned int level;
  88. AST_RWLIST_ENTRY(module_level) entry;
  89. char module[0];
  90. };
  91. AST_RWLIST_HEAD(module_level_list, module_level);
  92. /*! list of module names and their debug levels */
  93. static struct module_level_list debug_modules = AST_RWLIST_HEAD_INIT_VALUE;
  94. AST_THREADSTORAGE(ast_cli_buf);
  95. /*! \brief Initial buffer size for resulting strings in ast_cli() */
  96. #define AST_CLI_INITLEN 256
  97. void ast_cli(int fd, const char *fmt, ...)
  98. {
  99. int res;
  100. struct ast_str *buf;
  101. va_list ap;
  102. if (!(buf = ast_str_thread_get(&ast_cli_buf, AST_CLI_INITLEN)))
  103. return;
  104. va_start(ap, fmt);
  105. res = ast_str_set_va(&buf, 0, fmt, ap);
  106. va_end(ap);
  107. if (res != AST_DYNSTR_BUILD_FAILED) {
  108. ast_carefulwrite(fd, ast_str_buffer(buf), ast_str_strlen(buf), 100);
  109. }
  110. }
  111. unsigned int ast_debug_get_by_module(const char *module)
  112. {
  113. struct module_level *ml;
  114. unsigned int res = 0;
  115. AST_RWLIST_RDLOCK(&debug_modules);
  116. AST_LIST_TRAVERSE(&debug_modules, ml, entry) {
  117. if (!strcasecmp(ml->module, module)) {
  118. res = ml->level;
  119. break;
  120. }
  121. }
  122. AST_RWLIST_UNLOCK(&debug_modules);
  123. return res;
  124. }
  125. unsigned int ast_verbose_get_by_module(const char *module)
  126. {
  127. return 0;
  128. }
  129. /*! \internal
  130. * \brief Check if the user with 'uid' and 'gid' is allow to execute 'command',
  131. * if command starts with '_' then not check permissions, just permit
  132. * to run the 'command'.
  133. * if uid == -1 or gid == -1 do not check permissions.
  134. * if uid == -2 and gid == -2 is because rasterisk client didn't send
  135. * the credentials, so the cli_default_perm will be applied.
  136. * \param uid User ID.
  137. * \param gid Group ID.
  138. * \param command Command name to check permissions.
  139. * \retval 1 if has permission
  140. * \retval 0 if it is not allowed.
  141. */
  142. static int cli_has_permissions(int uid, int gid, const char *command)
  143. {
  144. struct usergroup_cli_perm *user_perm;
  145. struct cli_perm *perm;
  146. /* set to the default permissions general option. */
  147. int isallowg = cli_default_perm, isallowu = -1, ispattern;
  148. regex_t regexbuf;
  149. /* if uid == -1 or gid == -1 do not check permissions.
  150. if uid == -2 and gid == -2 is because rasterisk client didn't send
  151. the credentials, so the cli_default_perm will be applied. */
  152. if ((uid == CLI_NO_PERMS && gid == CLI_NO_PERMS) || command[0] == '_') {
  153. return 1;
  154. }
  155. if (gid < 0 && uid < 0) {
  156. return cli_default_perm;
  157. }
  158. AST_RWLIST_RDLOCK(&cli_perms);
  159. AST_LIST_TRAVERSE(&cli_perms, user_perm, list) {
  160. if (user_perm->gid != gid && user_perm->uid != uid) {
  161. continue;
  162. }
  163. AST_LIST_TRAVERSE(user_perm->perms, perm, list) {
  164. if (strcasecmp(perm->command, "all") && strncasecmp(perm->command, command, strlen(perm->command))) {
  165. /* if the perm->command is a pattern, check it against command. */
  166. ispattern = !regcomp(&regexbuf, perm->command, REG_EXTENDED | REG_NOSUB | REG_ICASE);
  167. if (ispattern && regexec(&regexbuf, command, 0, NULL, 0)) {
  168. regfree(&regexbuf);
  169. continue;
  170. }
  171. if (!ispattern) {
  172. continue;
  173. }
  174. regfree(&regexbuf);
  175. }
  176. if (user_perm->uid == uid) {
  177. /* this is a user definition. */
  178. isallowu = perm->permit;
  179. } else {
  180. /* otherwise is a group definition. */
  181. isallowg = perm->permit;
  182. }
  183. }
  184. }
  185. AST_RWLIST_UNLOCK(&cli_perms);
  186. if (isallowu > -1) {
  187. /* user definition override group definition. */
  188. isallowg = isallowu;
  189. }
  190. return isallowg;
  191. }
  192. static AST_RWLIST_HEAD_STATIC(helpers, ast_cli_entry);
  193. static char *complete_fn(const char *word, int state)
  194. {
  195. char *c, *d;
  196. char filename[PATH_MAX];
  197. if (word[0] == '/')
  198. ast_copy_string(filename, word, sizeof(filename));
  199. else
  200. snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_MODULE_DIR, word);
  201. c = d = filename_completion_function(filename, state);
  202. if (c && word[0] != '/')
  203. c += (strlen(ast_config_AST_MODULE_DIR) + 1);
  204. if (c)
  205. c = ast_strdup(c);
  206. ast_std_free(d);
  207. return c;
  208. }
  209. static char *handle_load(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  210. {
  211. /* "module load <mod>" */
  212. switch (cmd) {
  213. case CLI_INIT:
  214. e->command = "module load";
  215. e->usage =
  216. "Usage: module load <module name>\n"
  217. " Loads the specified module into Asterisk.\n";
  218. return NULL;
  219. case CLI_GENERATE:
  220. if (a->pos != e->args)
  221. return NULL;
  222. return complete_fn(a->word, a->n);
  223. }
  224. if (a->argc != e->args + 1)
  225. return CLI_SHOWUSAGE;
  226. if (ast_load_resource(a->argv[e->args])) {
  227. ast_cli(a->fd, "Unable to load module %s\n", a->argv[e->args]);
  228. return CLI_FAILURE;
  229. }
  230. ast_cli(a->fd, "Loaded %s\n", a->argv[e->args]);
  231. return CLI_SUCCESS;
  232. }
  233. static char *handle_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  234. {
  235. int x;
  236. switch (cmd) {
  237. case CLI_INIT:
  238. e->command = "module reload";
  239. e->usage =
  240. "Usage: module reload [module ...]\n"
  241. " Reloads configuration files for all listed modules which support\n"
  242. " reloading, or for all supported modules if none are listed.\n";
  243. return NULL;
  244. case CLI_GENERATE:
  245. return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 1);
  246. }
  247. if (a->argc == e->args) {
  248. ast_module_reload(NULL);
  249. return CLI_SUCCESS;
  250. }
  251. for (x = e->args; x < a->argc; x++) {
  252. enum ast_module_reload_result res = ast_module_reload(a->argv[x]);
  253. switch (res) {
  254. case AST_MODULE_RELOAD_NOT_FOUND:
  255. ast_cli(a->fd, "No such module '%s'\n", a->argv[x]);
  256. break;
  257. case AST_MODULE_RELOAD_NOT_IMPLEMENTED:
  258. ast_cli(a->fd, "The module '%s' does not support reloads\n", a->argv[x]);
  259. break;
  260. case AST_MODULE_RELOAD_QUEUED:
  261. ast_cli(a->fd, "Asterisk cannot reload a module yet; request queued\n");
  262. break;
  263. case AST_MODULE_RELOAD_ERROR:
  264. ast_cli(a->fd, "The module '%s' reported a reload failure\n", a->argv[x]);
  265. break;
  266. case AST_MODULE_RELOAD_IN_PROGRESS:
  267. ast_cli(a->fd, "A module reload request is already in progress; please be patient\n");
  268. break;
  269. case AST_MODULE_RELOAD_UNINITIALIZED:
  270. ast_cli(a->fd, "The module '%s' was not properly initialized. Before reloading"
  271. " the module, you must run \"module load %s\" and fix whatever is"
  272. " preventing the module from being initialized.\n", a->argv[x], a->argv[x]);
  273. break;
  274. case AST_MODULE_RELOAD_SUCCESS:
  275. ast_cli(a->fd, "Module '%s' reloaded successfully.\n", a->argv[x]);
  276. break;
  277. }
  278. }
  279. return CLI_SUCCESS;
  280. }
  281. static char *handle_core_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  282. {
  283. switch (cmd) {
  284. case CLI_INIT:
  285. e->command = "core reload";
  286. e->usage =
  287. "Usage: core reload\n"
  288. " Execute a global reload.\n";
  289. return NULL;
  290. case CLI_GENERATE:
  291. return NULL;
  292. }
  293. if (a->argc != e->args) {
  294. return CLI_SHOWUSAGE;
  295. }
  296. ast_module_reload(NULL);
  297. return CLI_SUCCESS;
  298. }
  299. /*!
  300. * \brief Find the module level setting
  301. *
  302. * \param module Module name to look for.
  303. * \param mll List to search.
  304. *
  305. * \retval level struct found on success.
  306. * \retval NULL not found.
  307. */
  308. static struct module_level *find_module_level(const char *module, struct module_level_list *mll)
  309. {
  310. struct module_level *ml;
  311. AST_LIST_TRAVERSE(mll, ml, entry) {
  312. if (!strcasecmp(ml->module, module))
  313. return ml;
  314. }
  315. return NULL;
  316. }
  317. static char *complete_number(const char *partial, unsigned int min, unsigned int max, int n)
  318. {
  319. int i, count = 0;
  320. unsigned int prospective[2];
  321. unsigned int part = strtoul(partial, NULL, 10);
  322. char next[12];
  323. if (part < min || part > max) {
  324. return NULL;
  325. }
  326. for (i = 0; i < 21; i++) {
  327. if (i == 0) {
  328. prospective[0] = prospective[1] = part;
  329. } else if (part == 0 && !ast_strlen_zero(partial)) {
  330. break;
  331. } else if (i < 11) {
  332. prospective[0] = prospective[1] = part * 10 + (i - 1);
  333. } else {
  334. prospective[0] = (part * 10 + (i - 11)) * 10;
  335. prospective[1] = prospective[0] + 9;
  336. }
  337. if (i < 11 && (prospective[0] < min || prospective[0] > max)) {
  338. continue;
  339. } else if (prospective[1] < min || prospective[0] > max) {
  340. continue;
  341. }
  342. if (++count > n) {
  343. if (i < 11) {
  344. snprintf(next, sizeof(next), "%u", prospective[0]);
  345. } else {
  346. snprintf(next, sizeof(next), "%u...", prospective[0] / 10);
  347. }
  348. return ast_strdup(next);
  349. }
  350. }
  351. return NULL;
  352. }
  353. static void status_debug_verbose(struct ast_cli_args *a, const char *what, int old_val, int cur_val)
  354. {
  355. char was_buf[30];
  356. const char *was;
  357. if (old_val) {
  358. snprintf(was_buf, sizeof(was_buf), "%d", old_val);
  359. was = was_buf;
  360. } else {
  361. was = "OFF";
  362. }
  363. if (old_val == cur_val) {
  364. ast_cli(a->fd, "%s is still %s.\n", what, was);
  365. } else {
  366. char now_buf[30];
  367. const char *now;
  368. if (cur_val) {
  369. snprintf(now_buf, sizeof(now_buf), "%d", cur_val);
  370. now = now_buf;
  371. } else {
  372. now = "OFF";
  373. }
  374. ast_cli(a->fd, "%s was %s and is now %s.\n", what, was, now);
  375. }
  376. }
  377. static char *handle_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  378. {
  379. int oldval;
  380. int newlevel;
  381. int atleast = 0;
  382. const char *argv3 = a->argv ? S_OR(a->argv[3], "") : "";
  383. struct module_level *ml;
  384. switch (cmd) {
  385. case CLI_INIT:
  386. e->command = "core set debug";
  387. e->usage =
  388. #if !defined(LOW_MEMORY)
  389. "Usage: core set debug [atleast] <level> [module]\n"
  390. #else
  391. "Usage: core set debug [atleast] <level>\n"
  392. #endif
  393. " core set debug off\n"
  394. "\n"
  395. #if !defined(LOW_MEMORY)
  396. " Sets level of debug messages to be displayed or\n"
  397. " sets a module name to display debug messages from.\n"
  398. #else
  399. " Sets level of debug messages to be displayed.\n"
  400. #endif
  401. " 0 or off means no messages should be displayed.\n"
  402. " Equivalent to -d[d[...]] on startup\n";
  403. return NULL;
  404. case CLI_GENERATE:
  405. if (!strcasecmp(argv3, "atleast")) {
  406. atleast = 1;
  407. }
  408. if (a->pos == 3 || (a->pos == 4 && atleast)) {
  409. const char *pos = a->pos == 3 ? argv3 : S_OR(a->argv[4], "");
  410. int numbermatch = (ast_strlen_zero(pos) || strchr("123456789", pos[0])) ? 0 : 21;
  411. if (a->n < 21 && numbermatch == 0) {
  412. return complete_number(pos, 0, 0x7fffffff, a->n);
  413. } else if (pos[0] == '0') {
  414. if (a->n == 0) {
  415. return ast_strdup("0");
  416. }
  417. } else if (a->n == (21 - numbermatch)) {
  418. if (a->pos == 3 && !strncasecmp(argv3, "off", strlen(argv3))) {
  419. return ast_strdup("off");
  420. } else if (a->pos == 3 && !strncasecmp(argv3, "atleast", strlen(argv3))) {
  421. return ast_strdup("atleast");
  422. }
  423. } else if (a->n == (22 - numbermatch) && a->pos == 3 && ast_strlen_zero(argv3)) {
  424. return ast_strdup("atleast");
  425. }
  426. #if !defined(LOW_MEMORY)
  427. } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off") && strcasecmp(argv3, "channel"))
  428. || (a->pos == 5 && atleast)) {
  429. const char *pos = S_OR(a->argv[a->pos], "");
  430. return ast_complete_source_filename(pos, a->n);
  431. #endif
  432. }
  433. return NULL;
  434. }
  435. /* all the above return, so we proceed with the handler.
  436. * we are guaranteed to be called with argc >= e->args;
  437. */
  438. if (a->argc <= e->args) {
  439. return CLI_SHOWUSAGE;
  440. }
  441. if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args], "off")) {
  442. newlevel = 0;
  443. } else {
  444. if (!strcasecmp(a->argv[e->args], "atleast")) {
  445. atleast = 1;
  446. }
  447. if (a->argc != e->args + atleast + 1 && a->argc != e->args + atleast + 2) {
  448. return CLI_SHOWUSAGE;
  449. }
  450. if (sscanf(a->argv[e->args + atleast], "%30d", &newlevel) != 1) {
  451. return CLI_SHOWUSAGE;
  452. }
  453. if (a->argc == e->args + atleast + 2) {
  454. /* We have specified a module name. */
  455. char *mod = ast_strdupa(a->argv[e->args + atleast + 1]);
  456. int mod_len = strlen(mod);
  457. if (3 < mod_len && !strcasecmp(mod + mod_len - 3, ".so")) {
  458. mod[mod_len - 3] = '\0';
  459. }
  460. AST_RWLIST_WRLOCK(&debug_modules);
  461. ml = find_module_level(mod, &debug_modules);
  462. if (!newlevel) {
  463. if (!ml) {
  464. /* Specified off for a nonexistent entry. */
  465. AST_RWLIST_UNLOCK(&debug_modules);
  466. ast_cli(a->fd, "Core debug is still 0 for '%s'.\n", mod);
  467. return CLI_SUCCESS;
  468. }
  469. AST_RWLIST_REMOVE(&debug_modules, ml, entry);
  470. if (AST_RWLIST_EMPTY(&debug_modules)) {
  471. ast_clear_flag(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
  472. }
  473. AST_RWLIST_UNLOCK(&debug_modules);
  474. ast_cli(a->fd, "Core debug was %u and has been set to 0 for '%s'.\n",
  475. ml->level, mod);
  476. ast_free(ml);
  477. return CLI_SUCCESS;
  478. }
  479. if (ml) {
  480. if ((atleast && newlevel < ml->level) || ml->level == newlevel) {
  481. ast_cli(a->fd, "Core debug is still %u for '%s'.\n", ml->level, mod);
  482. AST_RWLIST_UNLOCK(&debug_modules);
  483. return CLI_SUCCESS;
  484. }
  485. oldval = ml->level;
  486. ml->level = newlevel;
  487. } else {
  488. ml = ast_calloc(1, sizeof(*ml) + strlen(mod) + 1);
  489. if (!ml) {
  490. AST_RWLIST_UNLOCK(&debug_modules);
  491. return CLI_FAILURE;
  492. }
  493. oldval = ml->level;
  494. ml->level = newlevel;
  495. strcpy(ml->module, mod);
  496. AST_RWLIST_INSERT_TAIL(&debug_modules, ml, entry);
  497. }
  498. ast_set_flag(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
  499. ast_cli(a->fd, "Core debug was %d and has been set to %u for '%s'.\n",
  500. oldval, ml->level, ml->module);
  501. AST_RWLIST_UNLOCK(&debug_modules);
  502. return CLI_SUCCESS;
  503. }
  504. }
  505. /* Update global debug level */
  506. if (!newlevel) {
  507. /* Specified level was 0 or off. */
  508. AST_RWLIST_WRLOCK(&debug_modules);
  509. while ((ml = AST_RWLIST_REMOVE_HEAD(&debug_modules, entry))) {
  510. ast_free(ml);
  511. }
  512. ast_clear_flag(&ast_options, AST_OPT_FLAG_DEBUG_MODULE);
  513. AST_RWLIST_UNLOCK(&debug_modules);
  514. }
  515. oldval = option_debug;
  516. if (!atleast || newlevel > option_debug) {
  517. option_debug = newlevel;
  518. }
  519. /* Report debug level status */
  520. status_debug_verbose(a, "Core debug", oldval, option_debug);
  521. return CLI_SUCCESS;
  522. }
  523. static char *handle_verbose(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  524. {
  525. int oldval;
  526. int newlevel;
  527. int atleast = 0;
  528. int silent = 0;
  529. const char *argv3 = a->argv ? S_OR(a->argv[3], "") : "";
  530. switch (cmd) {
  531. case CLI_INIT:
  532. e->command = "core set verbose";
  533. e->usage =
  534. "Usage: core set verbose [atleast] <level> [silent]\n"
  535. " core set verbose off\n"
  536. "\n"
  537. " Sets level of verbose messages to be displayed.\n"
  538. " 0 or off means no verbose messages should be displayed.\n"
  539. " The silent option means the command does not report what\n"
  540. " happened to the verbose level.\n"
  541. " Equivalent to -v[v[...]] on startup\n";
  542. return NULL;
  543. case CLI_GENERATE:
  544. if (!strcasecmp(argv3, "atleast")) {
  545. atleast = 1;
  546. }
  547. if (a->pos == 3 || (a->pos == 4 && atleast)) {
  548. const char *pos = a->pos == 3 ? argv3 : S_OR(a->argv[4], "");
  549. int numbermatch = (ast_strlen_zero(pos) || strchr("123456789", pos[0])) ? 0 : 21;
  550. if (a->n < 21 && numbermatch == 0) {
  551. return complete_number(pos, 0, 0x7fffffff, a->n);
  552. } else if (pos[0] == '0') {
  553. if (a->n == 0) {
  554. return ast_strdup("0");
  555. }
  556. } else if (a->n == (21 - numbermatch)) {
  557. if (a->pos == 3 && !strncasecmp(argv3, "off", strlen(argv3))) {
  558. return ast_strdup("off");
  559. } else if (a->pos == 3 && !strncasecmp(argv3, "atleast", strlen(argv3))) {
  560. return ast_strdup("atleast");
  561. }
  562. } else if (a->n == (22 - numbermatch) && a->pos == 3 && ast_strlen_zero(argv3)) {
  563. return ast_strdup("atleast");
  564. }
  565. } else if ((a->pos == 4 && !atleast && strcasecmp(argv3, "off"))
  566. || (a->pos == 5 && atleast)) {
  567. const char *pos = S_OR(a->argv[a->pos], "");
  568. if (a->n == 0 && !strncasecmp(pos, "silent", strlen(pos))) {
  569. return ast_strdup("silent");
  570. }
  571. }
  572. return NULL;
  573. }
  574. /* all the above return, so we proceed with the handler.
  575. * we are guaranteed to be called with argc >= e->args;
  576. */
  577. if (a->argc <= e->args) {
  578. return CLI_SHOWUSAGE;
  579. }
  580. if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args], "off")) {
  581. newlevel = 0;
  582. } else {
  583. if (!strcasecmp(a->argv[e->args], "atleast")) {
  584. atleast = 1;
  585. }
  586. if (a->argc == e->args + atleast + 2
  587. && !strcasecmp(a->argv[e->args + atleast + 1], "silent")) {
  588. silent = 1;
  589. }
  590. if (a->argc != e->args + atleast + silent + 1) {
  591. return CLI_SHOWUSAGE;
  592. }
  593. if (sscanf(a->argv[e->args + atleast], "%30d", &newlevel) != 1) {
  594. return CLI_SHOWUSAGE;
  595. }
  596. }
  597. /* Update verbose level */
  598. oldval = ast_verb_console_get();
  599. if (!atleast || newlevel > oldval) {
  600. ast_verb_console_set(newlevel);
  601. } else {
  602. newlevel = oldval;
  603. }
  604. if (silent) {
  605. /* Be silent after setting the level. */
  606. return CLI_SUCCESS;
  607. }
  608. /* Report verbose level status */
  609. status_debug_verbose(a, "Console verbose", oldval, newlevel);
  610. return CLI_SUCCESS;
  611. }
  612. static char *handle_logger_mute(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  613. {
  614. switch (cmd) {
  615. case CLI_INIT:
  616. e->command = "logger mute";
  617. e->usage =
  618. "Usage: logger mute\n"
  619. " Disables logging output to the current console, making it possible to\n"
  620. " gather information without being disturbed by scrolling lines.\n";
  621. return NULL;
  622. case CLI_GENERATE:
  623. return NULL;
  624. }
  625. if (a->argc < 2 || a->argc > 3)
  626. return CLI_SHOWUSAGE;
  627. if (a->argc == 3 && !strcasecmp(a->argv[2], "silent"))
  628. ast_console_toggle_mute(a->fd, 1);
  629. else
  630. ast_console_toggle_mute(a->fd, 0);
  631. return CLI_SUCCESS;
  632. }
  633. static char *handle_unload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  634. {
  635. /* "module unload mod_1 [mod_2 .. mod_N]" */
  636. int x;
  637. int force = AST_FORCE_SOFT;
  638. const char *s;
  639. switch (cmd) {
  640. case CLI_INIT:
  641. e->command = "module unload";
  642. e->usage =
  643. "Usage: module unload [-f|-h] <module_1> [<module_2> ... ]\n"
  644. " Unloads the specified module from Asterisk. The -f\n"
  645. " option causes the module to be unloaded even if it is\n"
  646. " in use (may cause a crash) and the -h module causes the\n"
  647. " module to be unloaded even if the module says it cannot, \n"
  648. " which almost always will cause a crash.\n";
  649. return NULL;
  650. case CLI_GENERATE:
  651. return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
  652. }
  653. if (a->argc < e->args + 1)
  654. return CLI_SHOWUSAGE;
  655. x = e->args; /* first argument */
  656. s = a->argv[x];
  657. if (s[0] == '-') {
  658. if (s[1] == 'f')
  659. force = AST_FORCE_FIRM;
  660. else if (s[1] == 'h')
  661. force = AST_FORCE_HARD;
  662. else
  663. return CLI_SHOWUSAGE;
  664. if (a->argc < e->args + 2) /* need at least one module name */
  665. return CLI_SHOWUSAGE;
  666. x++; /* skip this argument */
  667. }
  668. for (; x < a->argc; x++) {
  669. if (ast_unload_resource(a->argv[x], force)) {
  670. ast_cli(a->fd, "Unable to unload resource %s\n", a->argv[x]);
  671. return CLI_FAILURE;
  672. }
  673. ast_cli(a->fd, "Unloaded %s\n", a->argv[x]);
  674. }
  675. return CLI_SUCCESS;
  676. }
  677. #define MODLIST_FORMAT "%-30s %-40.40s %-10d %-11s %13s\n"
  678. #define MODLIST_FORMAT2 "%-30s %-40.40s %-10s %-11s %13s\n"
  679. AST_MUTEX_DEFINE_STATIC(climodentrylock);
  680. static int climodentryfd = -1;
  681. static int modlist_modentry(const char *module, const char *description,
  682. int usecnt, const char *status, const char *like,
  683. enum ast_module_support_level support_level)
  684. {
  685. /* Comparing the like with the module */
  686. if (strcasestr(module, like) ) {
  687. ast_cli(climodentryfd, MODLIST_FORMAT, module, description, usecnt,
  688. status, ast_module_support_level_to_string(support_level));
  689. return 1;
  690. }
  691. return 0;
  692. }
  693. static void print_uptimestr(int fd, struct timeval timeval, const char *prefix, int printsec)
  694. {
  695. int x; /* the main part - years, weeks, etc. */
  696. struct ast_str *out;
  697. #define SECOND (1)
  698. #define MINUTE (SECOND*60)
  699. #define HOUR (MINUTE*60)
  700. #define DAY (HOUR*24)
  701. #define WEEK (DAY*7)
  702. #define YEAR (DAY*365)
  703. #define NEEDCOMMA(x) ((x)? ",": "") /* define if we need a comma */
  704. if (timeval.tv_sec < 0) /* invalid, nothing to show */
  705. return;
  706. if (printsec) { /* plain seconds output */
  707. ast_cli(fd, "%s: %lu\n", prefix, (u_long)timeval.tv_sec);
  708. return;
  709. }
  710. out = ast_str_alloca(256);
  711. if (timeval.tv_sec > YEAR) {
  712. x = (timeval.tv_sec / YEAR);
  713. timeval.tv_sec -= (x * YEAR);
  714. ast_str_append(&out, 0, "%d year%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
  715. }
  716. if (timeval.tv_sec > WEEK) {
  717. x = (timeval.tv_sec / WEEK);
  718. timeval.tv_sec -= (x * WEEK);
  719. ast_str_append(&out, 0, "%d week%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
  720. }
  721. if (timeval.tv_sec > DAY) {
  722. x = (timeval.tv_sec / DAY);
  723. timeval.tv_sec -= (x * DAY);
  724. ast_str_append(&out, 0, "%d day%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
  725. }
  726. if (timeval.tv_sec > HOUR) {
  727. x = (timeval.tv_sec / HOUR);
  728. timeval.tv_sec -= (x * HOUR);
  729. ast_str_append(&out, 0, "%d hour%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
  730. }
  731. if (timeval.tv_sec > MINUTE) {
  732. x = (timeval.tv_sec / MINUTE);
  733. timeval.tv_sec -= (x * MINUTE);
  734. ast_str_append(&out, 0, "%d minute%s%s ", x, ESS(x),NEEDCOMMA(timeval.tv_sec));
  735. }
  736. x = timeval.tv_sec;
  737. if (x > 0 || ast_str_strlen(out) == 0) /* if there is nothing, print 0 seconds */
  738. ast_str_append(&out, 0, "%d second%s ", x, ESS(x));
  739. ast_cli(fd, "%s: %s\n", prefix, ast_str_buffer(out));
  740. }
  741. static struct ast_cli_entry *cli_next(struct ast_cli_entry *e)
  742. {
  743. if (e) {
  744. return AST_LIST_NEXT(e, list);
  745. } else {
  746. return AST_LIST_FIRST(&helpers);
  747. }
  748. }
  749. static char * handle_showuptime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  750. {
  751. struct timeval curtime = ast_tvnow();
  752. int printsec;
  753. switch (cmd) {
  754. case CLI_INIT:
  755. e->command = "core show uptime [seconds]";
  756. e->usage =
  757. "Usage: core show uptime [seconds]\n"
  758. " Shows Asterisk uptime information.\n"
  759. " The seconds word returns the uptime in seconds only.\n";
  760. return NULL;
  761. case CLI_GENERATE:
  762. return NULL;
  763. }
  764. /* regular handler */
  765. if (a->argc == e->args && !strcasecmp(a->argv[e->args-1],"seconds"))
  766. printsec = 1;
  767. else if (a->argc == e->args-1)
  768. printsec = 0;
  769. else
  770. return CLI_SHOWUSAGE;
  771. if (ast_startuptime.tv_sec)
  772. print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
  773. if (ast_lastreloadtime.tv_sec)
  774. print_uptimestr(a->fd, ast_tvsub(curtime, ast_lastreloadtime), "Last reload", printsec);
  775. return CLI_SUCCESS;
  776. }
  777. static char *handle_modlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  778. {
  779. const char *like;
  780. switch (cmd) {
  781. case CLI_INIT:
  782. e->command = "module show [like]";
  783. e->usage =
  784. "Usage: module show [like keyword]\n"
  785. " Shows Asterisk modules currently in use, and usage statistics.\n";
  786. return NULL;
  787. case CLI_GENERATE:
  788. if (a->pos == e->args)
  789. return ast_module_helper(a->line, a->word, a->pos, a->n, a->pos, 0);
  790. else
  791. return NULL;
  792. }
  793. /* all the above return, so we proceed with the handler.
  794. * we are guaranteed to have argc >= e->args
  795. */
  796. if (a->argc == e->args - 1)
  797. like = "";
  798. else if (a->argc == e->args + 1 && !strcasecmp(a->argv[e->args-1], "like") )
  799. like = a->argv[e->args];
  800. else
  801. return CLI_SHOWUSAGE;
  802. ast_mutex_lock(&climodentrylock);
  803. climodentryfd = a->fd; /* global, protected by climodentrylock */
  804. ast_cli(a->fd, MODLIST_FORMAT2, "Module", "Description", "Use Count", "Status", "Support Level");
  805. ast_cli(a->fd,"%d modules loaded\n", ast_update_module_list(modlist_modentry, like));
  806. climodentryfd = -1;
  807. ast_mutex_unlock(&climodentrylock);
  808. return CLI_SUCCESS;
  809. }
  810. #undef MODLIST_FORMAT
  811. #undef MODLIST_FORMAT2
  812. static char *handle_showcalls(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  813. {
  814. struct timeval curtime = ast_tvnow();
  815. int showuptime, printsec;
  816. switch (cmd) {
  817. case CLI_INIT:
  818. e->command = "core show calls [uptime]";
  819. e->usage =
  820. "Usage: core show calls [uptime] [seconds]\n"
  821. " Lists number of currently active calls and total number of calls\n"
  822. " processed through PBX since last restart. If 'uptime' is specified\n"
  823. " the system uptime is also displayed. If 'seconds' is specified in\n"
  824. " addition to 'uptime', the system uptime is displayed in seconds.\n";
  825. return NULL;
  826. case CLI_GENERATE:
  827. if (a->pos != e->args)
  828. return NULL;
  829. return a->n == 0 ? ast_strdup("seconds") : NULL;
  830. }
  831. /* regular handler */
  832. if (a->argc >= e->args && !strcasecmp(a->argv[e->args-1],"uptime")) {
  833. showuptime = 1;
  834. if (a->argc == e->args+1 && !strcasecmp(a->argv[e->args],"seconds"))
  835. printsec = 1;
  836. else if (a->argc == e->args)
  837. printsec = 0;
  838. else
  839. return CLI_SHOWUSAGE;
  840. } else if (a->argc == e->args-1) {
  841. showuptime = 0;
  842. printsec = 0;
  843. } else
  844. return CLI_SHOWUSAGE;
  845. if (ast_option_maxcalls) {
  846. ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
  847. ast_active_calls(), ast_option_maxcalls, ESS(ast_active_calls()),
  848. ((double)ast_active_calls() / (double)ast_option_maxcalls) * 100.0);
  849. } else {
  850. ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
  851. }
  852. ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
  853. if (ast_startuptime.tv_sec && showuptime) {
  854. print_uptimestr(a->fd, ast_tvsub(curtime, ast_startuptime), "System uptime", printsec);
  855. }
  856. return RESULT_SUCCESS;
  857. }
  858. static char *handle_chanlist(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  859. {
  860. #define FORMAT_STRING "%-20.20s %-20.20s %-7.7s %-30.30s\n"
  861. #define FORMAT_STRING2 "%-20.20s %-20.20s %-7.7s %-30.30s\n"
  862. #define CONCISE_FORMAT_STRING "%s!%s!%s!%d!%s!%s!%s!%s!%s!%s!%d!%s!%s!%s\n"
  863. #define VERBOSE_FORMAT_STRING "%-20.20s %-20.20s %-16.16s %4d %-7.7s %-12.12s %-25.25s %-15.15s %8.8s %-11.11s %-11.11s %-20.20s\n"
  864. #define VERBOSE_FORMAT_STRING2 "%-20.20s %-20.20s %-16.16s %-4.4s %-7.7s %-12.12s %-25.25s %-15.15s %8.8s %-11.11s %-11.11s %-20.20s\n"
  865. RAII_VAR(struct ao2_container *, channels, NULL, ao2_cleanup);
  866. struct ao2_iterator it_chans;
  867. struct stasis_message *msg;
  868. int numchans = 0, concise = 0, verbose = 0, count = 0;
  869. switch (cmd) {
  870. case CLI_INIT:
  871. e->command = "core show channels [concise|verbose|count]";
  872. e->usage =
  873. "Usage: core show channels [concise|verbose|count]\n"
  874. " Lists currently defined channels and some information about them. If\n"
  875. " 'concise' is specified, the format is abridged and in a more easily\n"
  876. " machine parsable format. If 'verbose' is specified, the output includes\n"
  877. " more and longer fields. If 'count' is specified only the channel and call\n"
  878. " count is output.\n"
  879. " The 'concise' option is deprecated and will be removed from future versions\n"
  880. " of Asterisk.\n";
  881. return NULL;
  882. case CLI_GENERATE:
  883. return NULL;
  884. }
  885. if (a->argc == e->args) {
  886. if (!strcasecmp(a->argv[e->args-1],"concise"))
  887. concise = 1;
  888. else if (!strcasecmp(a->argv[e->args-1],"verbose"))
  889. verbose = 1;
  890. else if (!strcasecmp(a->argv[e->args-1],"count"))
  891. count = 1;
  892. else
  893. return CLI_SHOWUSAGE;
  894. } else if (a->argc != e->args - 1)
  895. return CLI_SHOWUSAGE;
  896. if (!(channels = stasis_cache_dump(ast_channel_cache_by_name(), ast_channel_snapshot_type()))) {
  897. ast_cli(a->fd, "Failed to retrieve cached channels\n");
  898. return CLI_SUCCESS;
  899. }
  900. if (!count) {
  901. if (!concise && !verbose)
  902. ast_cli(a->fd, FORMAT_STRING2, "Channel", "Location", "State", "Application(Data)");
  903. else if (verbose)
  904. ast_cli(a->fd, VERBOSE_FORMAT_STRING2, "Channel", "Context", "Extension", "Priority", "State", "Application", "Data",
  905. "CallerID", "Duration", "Accountcode", "PeerAccount", "BridgeID");
  906. }
  907. it_chans = ao2_iterator_init(channels, 0);
  908. for (; (msg = ao2_iterator_next(&it_chans)); ao2_ref(msg, -1)) {
  909. struct ast_channel_snapshot *cs = stasis_message_data(msg);
  910. char durbuf[10] = "-";
  911. if (!count) {
  912. if ((concise || verbose) && !ast_tvzero(cs->creationtime)) {
  913. int duration = (int)(ast_tvdiff_ms(ast_tvnow(), cs->creationtime) / 1000);
  914. if (verbose) {
  915. int durh = duration / 3600;
  916. int durm = (duration % 3600) / 60;
  917. int durs = duration % 60;
  918. snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
  919. } else {
  920. snprintf(durbuf, sizeof(durbuf), "%d", duration);
  921. }
  922. }
  923. if (concise) {
  924. ast_cli(a->fd, CONCISE_FORMAT_STRING, cs->name, cs->context, cs->exten, cs->priority, ast_state2str(cs->state),
  925. S_OR(cs->appl, "(None)"),
  926. cs->data,
  927. cs->caller_number,
  928. cs->accountcode,
  929. cs->peeraccount,
  930. cs->amaflags,
  931. durbuf,
  932. cs->bridgeid,
  933. cs->uniqueid);
  934. } else if (verbose) {
  935. ast_cli(a->fd, VERBOSE_FORMAT_STRING, cs->name, cs->context, cs->exten, cs->priority, ast_state2str(cs->state),
  936. S_OR(cs->appl, "(None)"),
  937. S_OR(cs->data, "(Empty)"),
  938. cs->caller_number,
  939. durbuf,
  940. cs->accountcode,
  941. cs->peeraccount,
  942. cs->bridgeid);
  943. } else {
  944. char locbuf[40] = "(None)";
  945. char appdata[40] = "(None)";
  946. if (!cs->context && !cs->exten)
  947. snprintf(locbuf, sizeof(locbuf), "%s@%s:%d", cs->exten, cs->context, cs->priority);
  948. if (cs->appl)
  949. snprintf(appdata, sizeof(appdata), "%s(%s)", cs->appl, S_OR(cs->data, ""));
  950. ast_cli(a->fd, FORMAT_STRING, cs->name, locbuf, ast_state2str(cs->state), appdata);
  951. }
  952. }
  953. }
  954. ao2_iterator_destroy(&it_chans);
  955. if (!concise) {
  956. numchans = ast_active_channels();
  957. ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
  958. if (ast_option_maxcalls)
  959. ast_cli(a->fd, "%d of %d max active call%s (%5.2f%% of capacity)\n",
  960. ast_active_calls(), ast_option_maxcalls, ESS(ast_active_calls()),
  961. ((double)ast_active_calls() / (double)ast_option_maxcalls) * 100.0);
  962. else
  963. ast_cli(a->fd, "%d active call%s\n", ast_active_calls(), ESS(ast_active_calls()));
  964. ast_cli(a->fd, "%d call%s processed\n", ast_processed_calls(), ESS(ast_processed_calls()));
  965. }
  966. return CLI_SUCCESS;
  967. #undef FORMAT_STRING
  968. #undef FORMAT_STRING2
  969. #undef CONCISE_FORMAT_STRING
  970. #undef VERBOSE_FORMAT_STRING
  971. #undef VERBOSE_FORMAT_STRING2
  972. }
  973. static char *handle_softhangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  974. {
  975. struct ast_channel *c=NULL;
  976. switch (cmd) {
  977. case CLI_INIT:
  978. e->command = "channel request hangup";
  979. e->usage =
  980. "Usage: channel request hangup <channel>|<all>\n"
  981. " Request that a channel be hung up. The hangup takes effect\n"
  982. " the next time the driver reads or writes from the channel.\n"
  983. " If 'all' is specified instead of a channel name, all channels\n"
  984. " will see the hangup request.\n";
  985. return NULL;
  986. case CLI_GENERATE:
  987. return ast_complete_channels(a->line, a->word, a->pos, a->n, e->args);
  988. }
  989. if (a->argc != 4) {
  990. return CLI_SHOWUSAGE;
  991. }
  992. if (!strcasecmp(a->argv[3], "all")) {
  993. struct ast_channel_iterator *iter = NULL;
  994. if (!(iter = ast_channel_iterator_all_new())) {
  995. return CLI_FAILURE;
  996. }
  997. for (; iter && (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
  998. ast_channel_lock(c);
  999. ast_cli(a->fd, "Requested Hangup on channel '%s'\n", ast_channel_name(c));
  1000. ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
  1001. ast_channel_unlock(c);
  1002. }
  1003. ast_channel_iterator_destroy(iter);
  1004. } else if ((c = ast_channel_get_by_name(a->argv[3]))) {
  1005. ast_channel_lock(c);
  1006. ast_cli(a->fd, "Requested Hangup on channel '%s'\n", ast_channel_name(c));
  1007. ast_softhangup(c, AST_SOFTHANGUP_EXPLICIT);
  1008. ast_channel_unlock(c);
  1009. c = ast_channel_unref(c);
  1010. } else {
  1011. ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
  1012. }
  1013. return CLI_SUCCESS;
  1014. }
  1015. /*! \brief handles CLI command 'cli show permissions' */
  1016. static char *handle_cli_show_permissions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1017. {
  1018. struct usergroup_cli_perm *cp;
  1019. struct cli_perm *perm;
  1020. struct passwd *pw = NULL;
  1021. struct group *gr = NULL;
  1022. switch (cmd) {
  1023. case CLI_INIT:
  1024. e->command = "cli show permissions";
  1025. e->usage =
  1026. "Usage: cli show permissions\n"
  1027. " Shows CLI configured permissions.\n";
  1028. return NULL;
  1029. case CLI_GENERATE:
  1030. return NULL;
  1031. }
  1032. AST_RWLIST_RDLOCK(&cli_perms);
  1033. AST_LIST_TRAVERSE(&cli_perms, cp, list) {
  1034. if (cp->uid >= 0) {
  1035. pw = getpwuid(cp->uid);
  1036. if (pw) {
  1037. ast_cli(a->fd, "user: %s [uid=%d]\n", pw->pw_name, cp->uid);
  1038. }
  1039. } else {
  1040. gr = getgrgid(cp->gid);
  1041. if (gr) {
  1042. ast_cli(a->fd, "group: %s [gid=%d]\n", gr->gr_name, cp->gid);
  1043. }
  1044. }
  1045. ast_cli(a->fd, "Permissions:\n");
  1046. if (cp->perms) {
  1047. AST_LIST_TRAVERSE(cp->perms, perm, list) {
  1048. ast_cli(a->fd, "\t%s -> %s\n", perm->permit ? "permit" : "deny", perm->command);
  1049. }
  1050. }
  1051. ast_cli(a->fd, "\n");
  1052. }
  1053. AST_RWLIST_UNLOCK(&cli_perms);
  1054. return CLI_SUCCESS;
  1055. }
  1056. /*! \brief handles CLI command 'cli reload permissions' */
  1057. static char *handle_cli_reload_permissions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1058. {
  1059. switch (cmd) {
  1060. case CLI_INIT:
  1061. e->command = "cli reload permissions";
  1062. e->usage =
  1063. "Usage: cli reload permissions\n"
  1064. " Reload the 'cli_permissions.conf' file.\n";
  1065. return NULL;
  1066. case CLI_GENERATE:
  1067. return NULL;
  1068. }
  1069. ast_cli_perms_init(1);
  1070. return CLI_SUCCESS;
  1071. }
  1072. /*! \brief handles CLI command 'cli check permissions' */
  1073. static char *handle_cli_check_permissions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1074. {
  1075. struct passwd *pw = NULL;
  1076. struct group *gr;
  1077. int gid = -1, uid = -1;
  1078. char command[AST_MAX_ARGS] = "";
  1079. struct ast_cli_entry *ce = NULL;
  1080. int found = 0;
  1081. char *group, *tmp;
  1082. switch (cmd) {
  1083. case CLI_INIT:
  1084. e->command = "cli check permissions";
  1085. e->usage =
  1086. "Usage: cli check permissions {<username>|@<groupname>|<username>@<groupname>} [<command>]\n"
  1087. " Check permissions config for a user@group or list the allowed commands for the specified user.\n"
  1088. " The username or the groupname may be omitted.\n";
  1089. return NULL;
  1090. case CLI_GENERATE:
  1091. if (a->pos >= 4) {
  1092. return ast_cli_generator(a->line + strlen("cli check permissions") + strlen(a->argv[3]) + 1, a->word, a->n);
  1093. }
  1094. return NULL;
  1095. }
  1096. if (a->argc < 4) {
  1097. return CLI_SHOWUSAGE;
  1098. }
  1099. tmp = ast_strdupa(a->argv[3]);
  1100. group = strchr(tmp, '@');
  1101. if (group) {
  1102. gr = getgrnam(&group[1]);
  1103. if (!gr) {
  1104. ast_cli(a->fd, "Unknown group '%s'\n", &group[1]);
  1105. return CLI_FAILURE;
  1106. }
  1107. group[0] = '\0';
  1108. gid = gr->gr_gid;
  1109. }
  1110. if (!group && ast_strlen_zero(tmp)) {
  1111. ast_cli(a->fd, "You didn't supply a username\n");
  1112. } else if (!ast_strlen_zero(tmp) && !(pw = getpwnam(tmp))) {
  1113. ast_cli(a->fd, "Unknown user '%s'\n", tmp);
  1114. return CLI_FAILURE;
  1115. } else if (pw) {
  1116. uid = pw->pw_uid;
  1117. }
  1118. if (a->argc == 4) {
  1119. while ((ce = cli_next(ce))) {
  1120. /* Hide commands that start with '_' */
  1121. if (ce->_full_cmd[0] == '_') {
  1122. continue;
  1123. }
  1124. if (cli_has_permissions(uid, gid, ce->_full_cmd)) {
  1125. ast_cli(a->fd, "%30.30s %s\n", ce->_full_cmd, S_OR(ce->summary, "<no description available>"));
  1126. found++;
  1127. }
  1128. }
  1129. if (!found) {
  1130. ast_cli(a->fd, "You are not allowed to run any command on Asterisk\n");
  1131. }
  1132. } else {
  1133. ast_join(command, sizeof(command), a->argv + 4);
  1134. ast_cli(a->fd, "%s '%s%s%s' is %s to run command: '%s'\n", uid >= 0 ? "User" : "Group", tmp,
  1135. group && uid >= 0 ? "@" : "",
  1136. group ? &group[1] : "",
  1137. cli_has_permissions(uid, gid, command) ? "allowed" : "not allowed", command);
  1138. }
  1139. return CLI_SUCCESS;
  1140. }
  1141. static char *__ast_cli_generator(const char *text, const char *word, int state, int lock);
  1142. static char *handle_commandmatchesarray(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1143. {
  1144. char *buf, *obuf;
  1145. int buflen = 2048;
  1146. int len = 0;
  1147. char **matches;
  1148. int x, matchlen;
  1149. switch (cmd) {
  1150. case CLI_INIT:
  1151. e->command = "_command matchesarray";
  1152. e->usage =
  1153. "Usage: _command matchesarray \"<line>\" text \n"
  1154. " This function is used internally to help with command completion and should.\n"
  1155. " never be called by the user directly.\n";
  1156. return NULL;
  1157. case CLI_GENERATE:
  1158. return NULL;
  1159. }
  1160. if (a->argc != 4)
  1161. return CLI_SHOWUSAGE;
  1162. if (!(buf = ast_malloc(buflen)))
  1163. return CLI_FAILURE;
  1164. buf[len] = '\0';
  1165. matches = ast_cli_completion_matches(a->argv[2], a->argv[3]);
  1166. if (matches) {
  1167. for (x=0; matches[x]; x++) {
  1168. matchlen = strlen(matches[x]) + 1;
  1169. if (len + matchlen >= buflen) {
  1170. buflen += matchlen * 3;
  1171. obuf = buf;
  1172. if (!(buf = ast_realloc(obuf, buflen)))
  1173. /* Memory allocation failure... Just free old buffer and be done */
  1174. ast_free(obuf);
  1175. }
  1176. if (buf)
  1177. len += sprintf( buf + len, "%s ", matches[x]);
  1178. ast_free(matches[x]);
  1179. matches[x] = NULL;
  1180. }
  1181. ast_free(matches);
  1182. }
  1183. if (buf) {
  1184. ast_cli(a->fd, "%s%s",buf, AST_CLI_COMPLETE_EOF);
  1185. ast_free(buf);
  1186. } else
  1187. ast_cli(a->fd, "NULL\n");
  1188. return CLI_SUCCESS;
  1189. }
  1190. static char *handle_commandnummatches(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1191. {
  1192. int matches = 0;
  1193. switch (cmd) {
  1194. case CLI_INIT:
  1195. e->command = "_command nummatches";
  1196. e->usage =
  1197. "Usage: _command nummatches \"<line>\" text \n"
  1198. " This function is used internally to help with command completion and should.\n"
  1199. " never be called by the user directly.\n";
  1200. return NULL;
  1201. case CLI_GENERATE:
  1202. return NULL;
  1203. }
  1204. if (a->argc != 4)
  1205. return CLI_SHOWUSAGE;
  1206. matches = ast_cli_generatornummatches(a->argv[2], a->argv[3]);
  1207. ast_cli(a->fd, "%d", matches);
  1208. return CLI_SUCCESS;
  1209. }
  1210. static char *handle_commandcomplete(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1211. {
  1212. char *buf;
  1213. switch (cmd) {
  1214. case CLI_INIT:
  1215. e->command = "_command complete";
  1216. e->usage =
  1217. "Usage: _command complete \"<line>\" text state\n"
  1218. " This function is used internally to help with command completion and should.\n"
  1219. " never be called by the user directly.\n";
  1220. return NULL;
  1221. case CLI_GENERATE:
  1222. return NULL;
  1223. }
  1224. if (a->argc != 5)
  1225. return CLI_SHOWUSAGE;
  1226. buf = __ast_cli_generator(a->argv[2], a->argv[3], atoi(a->argv[4]), 0);
  1227. if (buf) {
  1228. ast_cli(a->fd, "%s", buf);
  1229. ast_free(buf);
  1230. } else
  1231. ast_cli(a->fd, "NULL\n");
  1232. return CLI_SUCCESS;
  1233. }
  1234. struct channel_set_debug_args {
  1235. int fd;
  1236. int is_off;
  1237. };
  1238. static int channel_set_debug(void *obj, void *arg, void *data, int flags)
  1239. {
  1240. struct ast_channel *chan = obj;
  1241. struct channel_set_debug_args *args = data;
  1242. ast_channel_lock(chan);
  1243. if (!(ast_channel_fin(chan) & DEBUGCHAN_FLAG) || !(ast_channel_fout(chan) & DEBUGCHAN_FLAG)) {
  1244. if (args->is_off) {
  1245. ast_channel_fin_set(chan, ast_channel_fin(chan) & ~DEBUGCHAN_FLAG);
  1246. ast_channel_fout_set(chan, ast_channel_fout(chan) & ~DEBUGCHAN_FLAG);
  1247. } else {
  1248. ast_channel_fin_set(chan, ast_channel_fin(chan) | DEBUGCHAN_FLAG);
  1249. ast_channel_fout_set(chan, ast_channel_fout(chan) | DEBUGCHAN_FLAG);
  1250. }
  1251. ast_cli(args->fd, "Debugging %s on channel %s\n", args->is_off ? "disabled" : "enabled",
  1252. ast_channel_name(chan));
  1253. }
  1254. ast_channel_unlock(chan);
  1255. return 0;
  1256. }
  1257. static char *handle_core_set_debug_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1258. {
  1259. struct ast_channel *c = NULL;
  1260. struct channel_set_debug_args args = {
  1261. .fd = a->fd,
  1262. };
  1263. switch (cmd) {
  1264. case CLI_INIT:
  1265. e->command = "core set debug channel";
  1266. e->usage =
  1267. "Usage: core set debug channel <all|channel> [off]\n"
  1268. " Enables/disables debugging on all or on a specific channel.\n";
  1269. return NULL;
  1270. case CLI_GENERATE:
  1271. /* XXX remember to handle the optional "off" */
  1272. if (a->pos != e->args)
  1273. return NULL;
  1274. return a->n == 0 ? ast_strdup("all") : ast_complete_channels(a->line, a->word, a->pos, a->n - 1, e->args);
  1275. }
  1276. if (cmd == (CLI_HANDLER + 1000)) {
  1277. /* called from handle_nodebugchan_deprecated */
  1278. args.is_off = 1;
  1279. } else if (a->argc == e->args + 2) {
  1280. /* 'core set debug channel {all|chan_id}' */
  1281. if (!strcasecmp(a->argv[e->args + 1], "off"))
  1282. args.is_off = 1;
  1283. else
  1284. return CLI_SHOWUSAGE;
  1285. } else if (a->argc != e->args + 1) {
  1286. return CLI_SHOWUSAGE;
  1287. }
  1288. if (!strcasecmp("all", a->argv[e->args])) {
  1289. if (args.is_off) {
  1290. global_fin &= ~DEBUGCHAN_FLAG;
  1291. global_fout &= ~DEBUGCHAN_FLAG;
  1292. } else {
  1293. global_fin |= DEBUGCHAN_FLAG;
  1294. global_fout |= DEBUGCHAN_FLAG;
  1295. }
  1296. ast_channel_callback(channel_set_debug, NULL, &args, OBJ_NODATA | OBJ_MULTIPLE);
  1297. } else {
  1298. if ((c = ast_channel_get_by_name(a->argv[e->args]))) {
  1299. channel_set_debug(c, NULL, &args, 0);
  1300. ast_channel_unref(c);
  1301. } else {
  1302. ast_cli(a->fd, "No such channel %s\n", a->argv[e->args]);
  1303. }
  1304. }
  1305. ast_cli(a->fd, "Debugging on new channels is %s\n", args.is_off ? "disabled" : "enabled");
  1306. return CLI_SUCCESS;
  1307. }
  1308. static char *handle_nodebugchan_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1309. {
  1310. char *res;
  1311. switch (cmd) {
  1312. case CLI_INIT:
  1313. e->command = "no debug channel";
  1314. return NULL;
  1315. case CLI_HANDLER:
  1316. /* exit out of switch statement */
  1317. break;
  1318. default:
  1319. return NULL;
  1320. }
  1321. if (a->argc != e->args + 1)
  1322. return CLI_SHOWUSAGE;
  1323. /* add a 'magic' value to the CLI_HANDLER command so that
  1324. * handle_core_set_debug_channel() will act as if 'off'
  1325. * had been specified as part of the command
  1326. */
  1327. res = handle_core_set_debug_channel(e, CLI_HANDLER + 1000, a);
  1328. return res;
  1329. }
  1330. static char *handle_showchan(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1331. {
  1332. struct ast_channel *chan;
  1333. struct timeval now;
  1334. char cdrtime[256];
  1335. struct ast_str *obuf;/*!< Buffer for CDR variables. */
  1336. struct ast_str *output;/*!< Accumulation buffer for all output. */
  1337. long elapsed_seconds=0;
  1338. int hour=0, min=0, sec=0;
  1339. struct ast_var_t *var;
  1340. struct ast_str *write_transpath = ast_str_alloca(256);
  1341. struct ast_str *read_transpath = ast_str_alloca(256);
  1342. struct ast_str *codec_buf = ast_str_alloca(64);
  1343. struct ast_bridge *bridge;
  1344. struct ast_callid *callid;
  1345. char callid_buf[32];
  1346. switch (cmd) {
  1347. case CLI_INIT:
  1348. e->command = "core show channel";
  1349. e->usage =
  1350. "Usage: core show channel <channel>\n"
  1351. " Shows lots of information about the specified channel.\n";
  1352. return NULL;
  1353. case CLI_GENERATE:
  1354. return ast_complete_channels(a->line, a->word, a->pos, a->n, 3);
  1355. }
  1356. if (a->argc != 4) {
  1357. return CLI_SHOWUSAGE;
  1358. }
  1359. obuf = ast_str_thread_get(&ast_str_thread_global_buf, 16);
  1360. if (!obuf) {
  1361. return CLI_FAILURE;
  1362. }
  1363. output = ast_str_create(8192);
  1364. if (!output) {
  1365. return CLI_FAILURE;
  1366. }
  1367. chan = ast_channel_get_by_name(a->argv[3]);
  1368. if (!chan) {
  1369. ast_cli(a->fd, "%s is not a known channel\n", a->argv[3]);
  1370. return CLI_SUCCESS;
  1371. }
  1372. now = ast_tvnow();
  1373. ast_channel_lock(chan);
  1374. if (!ast_tvzero(ast_channel_creationtime(chan))) {
  1375. elapsed_seconds = now.tv_sec - ast_channel_creationtime(chan).tv_sec;
  1376. hour = elapsed_seconds / 3600;
  1377. min = (elapsed_seconds % 3600) / 60;
  1378. sec = elapsed_seconds % 60;
  1379. snprintf(cdrtime, sizeof(cdrtime), "%dh%dm%ds", hour, min, sec);
  1380. } else {
  1381. strcpy(cdrtime, "N/A");
  1382. }
  1383. ast_translate_path_to_str(ast_channel_writetrans(chan), &write_transpath);
  1384. ast_translate_path_to_str(ast_channel_readtrans(chan), &read_transpath);
  1385. bridge = ast_channel_get_bridge(chan);
  1386. callid_buf[0] = '\0';
  1387. callid = ast_channel_callid(chan);
  1388. if (callid) {
  1389. ast_callid_strnprint(callid_buf, sizeof(callid_buf), callid);
  1390. ast_callid_unref(callid);
  1391. }
  1392. ast_str_append(&output, 0,
  1393. " -- General --\n"
  1394. " Name: %s\n"
  1395. " Type: %s\n"
  1396. " UniqueID: %s\n"
  1397. " LinkedID: %s\n"
  1398. " Caller ID: %s\n"
  1399. " Caller ID Name: %s\n"
  1400. "Connected Line ID: %s\n"
  1401. "Connected Line ID Name: %s\n"
  1402. "Eff. Connected Line ID: %s\n"
  1403. "Eff. Connected Line ID Name: %s\n"
  1404. " DNID Digits: %s\n"
  1405. " Language: %s\n"
  1406. " State: %s (%u)\n"
  1407. " NativeFormats: %s\n"
  1408. " WriteFormat: %s\n"
  1409. " ReadFormat: %s\n"
  1410. " WriteTranscode: %s %s\n"
  1411. " ReadTranscode: %s %s\n"
  1412. " Time to Hangup: %ld\n"
  1413. " Elapsed Time: %s\n"
  1414. " Bridge ID: %s\n"
  1415. " -- PBX --\n"
  1416. " Context: %s\n"
  1417. " Extension: %s\n"
  1418. " Priority: %d\n"
  1419. " Call Group: %llu\n"
  1420. " Pickup Group: %llu\n"
  1421. " Application: %s\n"
  1422. " Data: %s\n"
  1423. " Call Identifer: %s\n",
  1424. ast_channel_name(chan),
  1425. ast_channel_tech(chan)->type,
  1426. ast_channel_uniqueid(chan),
  1427. ast_channel_linkedid(chan),
  1428. S_COR(ast_channel_caller(chan)->id.number.valid,
  1429. ast_channel_caller(chan)->id.number.str, "(N/A)"),
  1430. S_COR(ast_channel_caller(chan)->id.name.valid,
  1431. ast_channel_caller(chan)->id.name.str, "(N/A)"),
  1432. S_COR(ast_channel_connected(chan)->id.number.valid,
  1433. ast_channel_connected(chan)->id.number.str, "(N/A)"),
  1434. S_COR(ast_channel_connected(chan)->id.name.valid,
  1435. ast_channel_connected(chan)->id.name.str, "(N/A)"),
  1436. S_COR(ast_channel_connected_effective_id(chan).number.valid,
  1437. ast_channel_connected_effective_id(chan).number.str, "(N/A)"),
  1438. S_COR(ast_channel_connected_effective_id(chan).name.valid,
  1439. ast_channel_connected_effective_id(chan).name.str, "(N/A)"),
  1440. S_OR(ast_channel_dialed(chan)->number.str, "(N/A)"),
  1441. ast_channel_language(chan),
  1442. ast_state2str(ast_channel_state(chan)),
  1443. ast_channel_state(chan),
  1444. ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf),
  1445. ast_format_get_name(ast_channel_writeformat(chan)),
  1446. ast_format_get_name(ast_channel_readformat(chan)),
  1447. ast_str_strlen(write_transpath) ? "Yes" : "No",
  1448. ast_str_buffer(write_transpath),
  1449. ast_str_strlen(read_transpath) ? "Yes" : "No",
  1450. ast_str_buffer(read_transpath),
  1451. (long)ast_channel_whentohangup(chan)->tv_sec,
  1452. cdrtime,
  1453. bridge ? bridge->uniqueid : "(Not bridged)",
  1454. ast_channel_context(chan),
  1455. ast_channel_exten(chan),
  1456. ast_channel_priority(chan),
  1457. ast_channel_callgroup(chan),
  1458. ast_channel_pickupgroup(chan),
  1459. S_OR(ast_channel_appl(chan), "(N/A)"),
  1460. S_OR(ast_channel_data(chan), "(Empty)"),
  1461. S_OR(callid_buf, "(None)")
  1462. );
  1463. ast_str_append(&output, 0, " Variables:\n");
  1464. AST_LIST_TRAVERSE(ast_channel_varshead(chan), var, entries) {
  1465. ast_str_append(&output, 0, "%s=%s\n", ast_var_name(var), ast_var_value(var));
  1466. }
  1467. if (!(ast_channel_tech(chan)->properties & AST_CHAN_TP_INTERNAL)
  1468. && ast_cdr_serialize_variables(ast_channel_name(chan), &obuf, '=', '\n')) {
  1469. ast_str_append(&output, 0, " CDR Variables:\n%s\n", ast_str_buffer(obuf));
  1470. }
  1471. ast_channel_unlock(chan);
  1472. ast_cli(a->fd, "%s", ast_str_buffer(output));
  1473. ast_free(output);
  1474. ao2_cleanup(bridge);
  1475. ast_channel_unref(chan);
  1476. return CLI_SUCCESS;
  1477. }
  1478. /*
  1479. * helper function to generate CLI matches from a fixed set of values.
  1480. * A NULL word is acceptable.
  1481. */
  1482. char *ast_cli_complete(const char *word, const char * const choices[], int state)
  1483. {
  1484. int i, which = 0, len;
  1485. len = ast_strlen_zero(word) ? 0 : strlen(word);
  1486. for (i = 0; choices[i]; i++) {
  1487. if ((!len || !strncasecmp(word, choices[i], len)) && ++which > state)
  1488. return ast_strdup(choices[i]);
  1489. }
  1490. return NULL;
  1491. }
  1492. char *ast_complete_channels(const char *line, const char *word, int pos, int state, int rpos)
  1493. {
  1494. int wordlen = strlen(word), which = 0;
  1495. RAII_VAR(struct ao2_container *, cached_channels, NULL, ao2_cleanup);
  1496. char *ret = NULL;
  1497. struct ao2_iterator iter;
  1498. struct stasis_message *msg;
  1499. if (pos != rpos) {
  1500. return NULL;
  1501. }
  1502. if (!(cached_channels = stasis_cache_dump(ast_channel_cache(), ast_channel_snapshot_type()))) {
  1503. return NULL;
  1504. }
  1505. iter = ao2_iterator_init(cached_channels, 0);
  1506. for (; (msg = ao2_iterator_next(&iter)); ao2_ref(msg, -1)) {
  1507. struct ast_channel_snapshot *snapshot = stasis_message_data(msg);
  1508. if (!strncasecmp(word, snapshot->name, wordlen) && (++which > state)) {
  1509. ret = ast_strdup(snapshot->name);
  1510. ao2_ref(msg, -1);
  1511. break;
  1512. }
  1513. }
  1514. ao2_iterator_destroy(&iter);
  1515. return ret;
  1516. }
  1517. static char *group_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1518. {
  1519. #define FORMAT_STRING "%-25s %-20s %-20s\n"
  1520. struct ast_group_info *gi = NULL;
  1521. int numchans = 0;
  1522. regex_t regexbuf;
  1523. int havepattern = 0;
  1524. switch (cmd) {
  1525. case CLI_INIT:
  1526. e->command = "group show channels";
  1527. e->usage =
  1528. "Usage: group show channels [pattern]\n"
  1529. " Lists all currently active channels with channel group(s) specified.\n"
  1530. " Optional regular expression pattern is matched to group names for each\n"
  1531. " channel.\n";
  1532. return NULL;
  1533. case CLI_GENERATE:
  1534. return NULL;
  1535. }
  1536. if (a->argc < 3 || a->argc > 4)
  1537. return CLI_SHOWUSAGE;
  1538. if (a->argc == 4) {
  1539. if (regcomp(&regexbuf, a->argv[3], REG_EXTENDED | REG_NOSUB))
  1540. return CLI_SHOWUSAGE;
  1541. havepattern = 1;
  1542. }
  1543. ast_cli(a->fd, FORMAT_STRING, "Channel", "Group", "Category");
  1544. ast_app_group_list_rdlock();
  1545. gi = ast_app_group_list_head();
  1546. while (gi) {
  1547. if (!havepattern || !regexec(&regexbuf, gi->group, 0, NULL, 0)) {
  1548. ast_cli(a->fd, FORMAT_STRING, ast_channel_name(gi->chan), gi->group, (ast_strlen_zero(gi->category) ? "(default)" : gi->category));
  1549. numchans++;
  1550. }
  1551. gi = AST_LIST_NEXT(gi, group_list);
  1552. }
  1553. ast_app_group_list_unlock();
  1554. if (havepattern)
  1555. regfree(&regexbuf);
  1556. ast_cli(a->fd, "%d active channel%s\n", numchans, ESS(numchans));
  1557. return CLI_SUCCESS;
  1558. #undef FORMAT_STRING
  1559. }
  1560. static char *handle_cli_wait_fullybooted(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1561. {
  1562. switch (cmd) {
  1563. case CLI_INIT:
  1564. e->command = "core waitfullybooted";
  1565. e->usage =
  1566. "Usage: core waitfullybooted\n"
  1567. " Wait until Asterisk has fully booted.\n";
  1568. return NULL;
  1569. case CLI_GENERATE:
  1570. return NULL;
  1571. }
  1572. while (!ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)) {
  1573. usleep(100);
  1574. }
  1575. ast_cli(a->fd, "Asterisk has fully booted.\n");
  1576. return CLI_SUCCESS;
  1577. }
  1578. static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
  1579. static struct ast_cli_entry cli_cli[] = {
  1580. /* Deprecated, but preferred command is now consolidated (and already has a deprecated command for it). */
  1581. AST_CLI_DEFINE(handle_commandcomplete, "Command complete"),
  1582. AST_CLI_DEFINE(handle_commandnummatches, "Returns number of command matches"),
  1583. AST_CLI_DEFINE(handle_commandmatchesarray, "Returns command matches array"),
  1584. AST_CLI_DEFINE(handle_nodebugchan_deprecated, "Disable debugging on channel(s)"),
  1585. AST_CLI_DEFINE(handle_chanlist, "Display information on channels"),
  1586. AST_CLI_DEFINE(handle_showcalls, "Display information on calls"),
  1587. AST_CLI_DEFINE(handle_showchan, "Display information on a specific channel"),
  1588. AST_CLI_DEFINE(handle_core_set_debug_channel, "Enable/disable debugging on a channel"),
  1589. AST_CLI_DEFINE(handle_debug, "Set level of debug chattiness"),
  1590. AST_CLI_DEFINE(handle_verbose, "Set level of verbose chattiness"),
  1591. AST_CLI_DEFINE(group_show_channels, "Display active channels with group(s)"),
  1592. AST_CLI_DEFINE(handle_help, "Display help list, or specific help on a command"),
  1593. AST_CLI_DEFINE(handle_logger_mute, "Toggle logging output to a console"),
  1594. AST_CLI_DEFINE(handle_modlist, "List modules and info"),
  1595. AST_CLI_DEFINE(handle_load, "Load a module by name"),
  1596. AST_CLI_DEFINE(handle_reload, "Reload configuration for a module"),
  1597. AST_CLI_DEFINE(handle_core_reload, "Global reload"),
  1598. AST_CLI_DEFINE(handle_unload, "Unload a module by name"),
  1599. AST_CLI_DEFINE(handle_showuptime, "Show uptime information"),
  1600. AST_CLI_DEFINE(handle_softhangup, "Request a hangup on a given channel"),
  1601. AST_CLI_DEFINE(handle_cli_reload_permissions, "Reload CLI permissions config"),
  1602. AST_CLI_DEFINE(handle_cli_show_permissions, "Show CLI permissions"),
  1603. AST_CLI_DEFINE(handle_cli_check_permissions, "Try a permissions config for a user"),
  1604. AST_CLI_DEFINE(handle_cli_wait_fullybooted, "Wait for Asterisk to be fully booted"),
  1605. };
  1606. /*!
  1607. * Some regexp characters in cli arguments are reserved and used as separators.
  1608. */
  1609. static const char cli_rsvd[] = "[]{}|*%";
  1610. /*!
  1611. * initialize the _full_cmd string and related parameters,
  1612. * return 0 on success, -1 on error.
  1613. */
  1614. static int set_full_cmd(struct ast_cli_entry *e)
  1615. {
  1616. int i;
  1617. char buf[80];
  1618. ast_join(buf, sizeof(buf), e->cmda);
  1619. e->_full_cmd = ast_strdup(buf);
  1620. if (!e->_full_cmd) {
  1621. ast_log(LOG_WARNING, "-- cannot allocate <%s>\n", buf);
  1622. return -1;
  1623. }
  1624. e->cmdlen = strcspn(e->_full_cmd, cli_rsvd);
  1625. for (i = 0; e->cmda[i]; i++)
  1626. ;
  1627. e->args = i;
  1628. return 0;
  1629. }
  1630. /*! \brief cleanup (free) cli_perms linkedlist. */
  1631. static void destroy_user_perms(void)
  1632. {
  1633. struct cli_perm *perm;
  1634. struct usergroup_cli_perm *user_perm;
  1635. AST_RWLIST_WRLOCK(&cli_perms);
  1636. while ((user_perm = AST_LIST_REMOVE_HEAD(&cli_perms, list))) {
  1637. while ((perm = AST_LIST_REMOVE_HEAD(user_perm->perms, list))) {
  1638. ast_free(perm->command);
  1639. ast_free(perm);
  1640. }
  1641. ast_free(user_perm);
  1642. }
  1643. AST_RWLIST_UNLOCK(&cli_perms);
  1644. }
  1645. int ast_cli_perms_init(int reload)
  1646. {
  1647. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  1648. struct ast_config *cfg;
  1649. char *cat = NULL;
  1650. struct ast_variable *v;
  1651. struct usergroup_cli_perm *user_group, *cp_entry;
  1652. struct cli_perm *perm = NULL;
  1653. struct passwd *pw;
  1654. struct group *gr;
  1655. if (ast_mutex_trylock(&permsconfiglock)) {
  1656. ast_log(LOG_NOTICE, "You must wait until last 'cli reload permissions' command finish\n");
  1657. return 1;
  1658. }
  1659. cfg = ast_config_load2(perms_config, "" /* core, can't reload */, config_flags);
  1660. if (!cfg) {
  1661. ast_mutex_unlock(&permsconfiglock);
  1662. return 1;
  1663. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  1664. ast_mutex_unlock(&permsconfiglock);
  1665. return 0;
  1666. }
  1667. /* free current structures. */
  1668. destroy_user_perms();
  1669. while ((cat = ast_category_browse(cfg, cat))) {
  1670. if (!strcasecmp(cat, "general")) {
  1671. /* General options */
  1672. for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
  1673. if (!strcasecmp(v->name, "default_perm")) {
  1674. cli_default_perm = (!strcasecmp(v->value, "permit")) ? 1: 0;
  1675. }
  1676. }
  1677. continue;
  1678. }
  1679. /* users or groups */
  1680. gr = NULL, pw = NULL;
  1681. if (cat[0] == '@') {
  1682. /* This is a group */
  1683. gr = getgrnam(&cat[1]);
  1684. if (!gr) {
  1685. ast_log (LOG_WARNING, "Unknown group '%s'\n", &cat[1]);
  1686. continue;
  1687. }
  1688. } else {
  1689. /* This is a user */
  1690. pw = getpwnam(cat);
  1691. if (!pw) {
  1692. ast_log (LOG_WARNING, "Unknown user '%s'\n", cat);
  1693. continue;
  1694. }
  1695. }
  1696. user_group = NULL;
  1697. /* Check for duplicates */
  1698. AST_RWLIST_WRLOCK(&cli_perms);
  1699. AST_LIST_TRAVERSE(&cli_perms, cp_entry, list) {
  1700. if ((pw && cp_entry->uid == pw->pw_uid) || (gr && cp_entry->gid == gr->gr_gid)) {
  1701. /* if it is duplicated, just added this new settings, to
  1702. the current list. */
  1703. user_group = cp_entry;
  1704. break;
  1705. }
  1706. }
  1707. AST_RWLIST_UNLOCK(&cli_perms);
  1708. if (!user_group) {
  1709. /* alloc space for the new user config. */
  1710. user_group = ast_calloc(1, sizeof(*user_group));
  1711. if (!user_group) {
  1712. continue;
  1713. }
  1714. user_group->uid = (pw ? pw->pw_uid : -1);
  1715. user_group->gid = (gr ? gr->gr_gid : -1);
  1716. user_group->perms = ast_calloc(1, sizeof(*user_group->perms));
  1717. if (!user_group->perms) {
  1718. ast_free(user_group);
  1719. continue;
  1720. }
  1721. }
  1722. for (v = ast_variable_browse(cfg, cat); v; v = v->next) {
  1723. if (ast_strlen_zero(v->value)) {
  1724. /* we need to check this condition cause it could break security. */
  1725. ast_log(LOG_WARNING, "Empty permit/deny option in user '%s'\n", cat);
  1726. continue;
  1727. }
  1728. if (!strcasecmp(v->name, "permit")) {
  1729. perm = ast_calloc(1, sizeof(*perm));
  1730. if (perm) {
  1731. perm->permit = 1;
  1732. perm->command = ast_strdup(v->value);
  1733. }
  1734. } else if (!strcasecmp(v->name, "deny")) {
  1735. perm = ast_calloc(1, sizeof(*perm));
  1736. if (perm) {
  1737. perm->permit = 0;
  1738. perm->command = ast_strdup(v->value);
  1739. }
  1740. } else {
  1741. /* up to now, only 'permit' and 'deny' are possible values. */
  1742. ast_log(LOG_WARNING, "Unknown '%s' option\n", v->name);
  1743. continue;
  1744. }
  1745. if (perm) {
  1746. /* Added the permission to the user's list. */
  1747. AST_LIST_INSERT_TAIL(user_group->perms, perm, list);
  1748. perm = NULL;
  1749. }
  1750. }
  1751. AST_RWLIST_WRLOCK(&cli_perms);
  1752. AST_RWLIST_INSERT_TAIL(&cli_perms, user_group, list);
  1753. AST_RWLIST_UNLOCK(&cli_perms);
  1754. }
  1755. ast_config_destroy(cfg);
  1756. ast_mutex_unlock(&permsconfiglock);
  1757. return 0;
  1758. }
  1759. static void cli_shutdown(void)
  1760. {
  1761. ast_cli_unregister_multiple(cli_cli, ARRAY_LEN(cli_cli));
  1762. }
  1763. /*! \brief initialize the _full_cmd string in * each of the builtins. */
  1764. void ast_builtins_init(void)
  1765. {
  1766. ast_cli_register_multiple(cli_cli, ARRAY_LEN(cli_cli));
  1767. ast_register_cleanup(cli_shutdown);
  1768. }
  1769. /*!
  1770. * match a word in the CLI entry.
  1771. * returns -1 on mismatch, 0 on match of an optional word,
  1772. * 1 on match of a full word.
  1773. *
  1774. * The pattern can be
  1775. * any_word match for equal
  1776. * [foo|bar|baz] optionally, one of these words
  1777. * {foo|bar|baz} exactly, one of these words
  1778. * % any word
  1779. */
  1780. static int word_match(const char *cmd, const char *cli_word)
  1781. {
  1782. int l;
  1783. char *pos;
  1784. if (ast_strlen_zero(cmd) || ast_strlen_zero(cli_word))
  1785. return -1;
  1786. if (!strchr(cli_rsvd, cli_word[0])) /* normal match */
  1787. return (strcasecmp(cmd, cli_word) == 0) ? 1 : -1;
  1788. l = strlen(cmd);
  1789. /* wildcard match - will extend in the future */
  1790. if (l > 0 && cli_word[0] == '%') {
  1791. return 1; /* wildcard */
  1792. }
  1793. /* Start a search for the command entered against the cli word in question */
  1794. pos = strcasestr(cli_word, cmd);
  1795. while (pos) {
  1796. /*
  1797. *Check if the word matched with is surrounded by reserved characters on both sides
  1798. * and isn't at the beginning of the cli_word since that would make it check in a location we shouldn't know about.
  1799. * If it is surrounded by reserved chars and isn't at the beginning, it's a match.
  1800. */
  1801. if (pos != cli_word && strchr(cli_rsvd, pos[-1]) && strchr(cli_rsvd, pos[l])) {
  1802. return 1; /* valid match */
  1803. }
  1804. /* Ok, that one didn't match, strcasestr to the next appearance of the command and start over.*/
  1805. pos = strcasestr(pos + 1, cmd);
  1806. }
  1807. /* If no matches were found over the course of the while loop, we hit the end of the string. It's a mismatch. */
  1808. return -1;
  1809. }
  1810. /*! \brief if word is a valid prefix for token, returns the pos-th
  1811. * match as a malloced string, or NULL otherwise.
  1812. * Always tell in *actual how many matches we got.
  1813. */
  1814. static char *is_prefix(const char *word, const char *token,
  1815. int pos, int *actual)
  1816. {
  1817. int lw;
  1818. char *s, *t1;
  1819. *actual = 0;
  1820. if (ast_strlen_zero(token))
  1821. return NULL;
  1822. if (ast_strlen_zero(word))
  1823. word = ""; /* dummy */
  1824. lw = strlen(word);
  1825. if (strcspn(word, cli_rsvd) != lw)
  1826. return NULL; /* no match if word has reserved chars */
  1827. if (strchr(cli_rsvd, token[0]) == NULL) { /* regular match */
  1828. if (strncasecmp(token, word, lw)) /* no match */
  1829. return NULL;
  1830. *actual = 1;
  1831. return (pos != 0) ? NULL : ast_strdup(token);
  1832. }
  1833. /* now handle regexp match */
  1834. /* Wildcard always matches, so we never do is_prefix on them */
  1835. t1 = ast_strdupa(token + 1); /* copy, skipping first char */
  1836. while (pos >= 0 && (s = strsep(&t1, cli_rsvd)) && *s) {
  1837. if (*s == '%') /* wildcard */
  1838. continue;
  1839. if (strncasecmp(s, word, lw)) /* no match */
  1840. continue;
  1841. (*actual)++;
  1842. if (pos-- == 0)
  1843. return ast_strdup(s);
  1844. }
  1845. return NULL;
  1846. }
  1847. /*!
  1848. * \internal
  1849. * \brief locate a cli command in the 'helpers' list (which must be locked).
  1850. * The search compares word by word taking care of regexps in e->cmda
  1851. * This function will return NULL when nothing is matched, or the ast_cli_entry that matched.
  1852. * \param cmds
  1853. * \param match_type has 3 possible values:
  1854. * 0 returns if the search key is equal or longer than the entry.
  1855. * note that trailing optional arguments are skipped.
  1856. * -1 true if the mismatch is on the last word XXX not true!
  1857. * 1 true only on complete, exact match.
  1858. *
  1859. */
  1860. static struct ast_cli_entry *find_cli(const char * const cmds[], int match_type)
  1861. {
  1862. int matchlen = -1; /* length of longest match so far */
  1863. struct ast_cli_entry *cand = NULL, *e=NULL;
  1864. while ( (e = cli_next(e)) ) {
  1865. /* word-by word regexp comparison */
  1866. const char * const *src = cmds;
  1867. const char * const *dst = e->cmda;
  1868. int n = 0;
  1869. for (;; dst++, src += n) {
  1870. n = word_match(*src, *dst);
  1871. if (n < 0)
  1872. break;
  1873. }
  1874. if (ast_strlen_zero(*dst) || ((*dst)[0] == '[' && ast_strlen_zero(dst[1]))) {
  1875. /* no more words in 'e' */
  1876. if (ast_strlen_zero(*src)) /* exact match, cannot do better */
  1877. break;
  1878. /* Here, cmds has more words than the entry 'e' */
  1879. if (match_type != 0) /* but we look for almost exact match... */
  1880. continue; /* so we skip this one. */
  1881. /* otherwise we like it (case 0) */
  1882. } else { /* still words in 'e' */
  1883. if (ast_strlen_zero(*src))
  1884. continue; /* cmds is shorter than 'e', not good */
  1885. /* Here we have leftover words in cmds and 'e',
  1886. * but there is a mismatch. We only accept this one if match_type == -1
  1887. * and this is the last word for both.
  1888. */
  1889. if (match_type != -1 || !ast_strlen_zero(src[1]) ||
  1890. !ast_strlen_zero(dst[1])) /* not the one we look for */
  1891. continue;
  1892. /* good, we are in case match_type == -1 and mismatch on last word */
  1893. }
  1894. if (src - cmds > matchlen) { /* remember the candidate */
  1895. matchlen = src - cmds;
  1896. cand = e;
  1897. }
  1898. }
  1899. return e ? e : cand;
  1900. }
  1901. static char *find_best(const char *argv[])
  1902. {
  1903. static char cmdline[80];
  1904. int x;
  1905. /* See how close we get, then print the candidate */
  1906. const char *myargv[AST_MAX_CMD_LEN] = { NULL, };
  1907. AST_RWLIST_RDLOCK(&helpers);
  1908. for (x = 0; argv[x]; x++) {
  1909. myargv[x] = argv[x];
  1910. if (!find_cli(myargv, -1))
  1911. break;
  1912. }
  1913. AST_RWLIST_UNLOCK(&helpers);
  1914. ast_join(cmdline, sizeof(cmdline), myargv);
  1915. return cmdline;
  1916. }
  1917. static int cli_is_registered(struct ast_cli_entry *e)
  1918. {
  1919. struct ast_cli_entry *cur = NULL;
  1920. while ((cur = cli_next(cur))) {
  1921. if (cur == e) {
  1922. return 1;
  1923. }
  1924. }
  1925. return 0;
  1926. }
  1927. static int __ast_cli_unregister(struct ast_cli_entry *e, struct ast_cli_entry *ed)
  1928. {
  1929. if (e->inuse) {
  1930. ast_log(LOG_WARNING, "Can't remove command that is in use\n");
  1931. } else {
  1932. AST_RWLIST_WRLOCK(&helpers);
  1933. AST_RWLIST_REMOVE(&helpers, e, list);
  1934. AST_RWLIST_UNLOCK(&helpers);
  1935. ast_free(e->_full_cmd);
  1936. e->_full_cmd = NULL;
  1937. if (e->handler) {
  1938. /* this is a new-style entry. Reset fields and free memory. */
  1939. char *cmda = (char *) e->cmda;
  1940. memset(cmda, '\0', sizeof(e->cmda));
  1941. ast_free(e->command);
  1942. e->command = NULL;
  1943. e->usage = NULL;
  1944. }
  1945. }
  1946. return 0;
  1947. }
  1948. static int __ast_cli_register(struct ast_cli_entry *e, struct ast_cli_entry *ed)
  1949. {
  1950. struct ast_cli_entry *cur;
  1951. int i, lf, ret = -1;
  1952. struct ast_cli_args a; /* fake argument */
  1953. char **dst = (char **)e->cmda; /* need to cast as the entry is readonly */
  1954. char *s;
  1955. AST_RWLIST_WRLOCK(&helpers);
  1956. if (cli_is_registered(e)) {
  1957. ast_log(LOG_WARNING, "Command '%s' already registered (the same ast_cli_entry)\n",
  1958. S_OR(e->_full_cmd, e->command));
  1959. ret = 0; /* report success */
  1960. goto done;
  1961. }
  1962. memset(&a, '\0', sizeof(a));
  1963. e->handler(e, CLI_INIT, &a);
  1964. /* XXX check that usage and command are filled up */
  1965. s = ast_skip_blanks(e->command);
  1966. s = e->command = ast_strdup(s);
  1967. for (i=0; !ast_strlen_zero(s) && i < AST_MAX_CMD_LEN-1; i++) {
  1968. *dst++ = s; /* store string */
  1969. s = ast_skip_nonblanks(s);
  1970. if (*s == '\0') /* we are done */
  1971. break;
  1972. *s++ = '\0';
  1973. s = ast_skip_blanks(s);
  1974. }
  1975. *dst++ = NULL;
  1976. if (find_cli(e->cmda, 1)) {
  1977. ast_log(LOG_WARNING, "Command '%s' already registered (or something close enough)\n",
  1978. S_OR(e->_full_cmd, e->command));
  1979. goto done;
  1980. }
  1981. if (set_full_cmd(e)) {
  1982. ast_log(LOG_WARNING, "Error registering CLI Command '%s'\n",
  1983. S_OR(e->_full_cmd, e->command));
  1984. goto done;
  1985. }
  1986. lf = e->cmdlen;
  1987. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&helpers, cur, list) {
  1988. int len = cur->cmdlen;
  1989. if (lf < len)
  1990. len = lf;
  1991. if (strncasecmp(e->_full_cmd, cur->_full_cmd, len) < 0) {
  1992. AST_RWLIST_INSERT_BEFORE_CURRENT(e, list);
  1993. break;
  1994. }
  1995. }
  1996. AST_RWLIST_TRAVERSE_SAFE_END;
  1997. if (!cur)
  1998. AST_RWLIST_INSERT_TAIL(&helpers, e, list);
  1999. ret = 0; /* success */
  2000. done:
  2001. AST_RWLIST_UNLOCK(&helpers);
  2002. if (ret) {
  2003. ast_free(e->command);
  2004. e->command = NULL;
  2005. }
  2006. return ret;
  2007. }
  2008. /* wrapper function, so we can unregister deprecated commands recursively */
  2009. int ast_cli_unregister(struct ast_cli_entry *e)
  2010. {
  2011. return __ast_cli_unregister(e, NULL);
  2012. }
  2013. /* wrapper function, so we can register deprecated commands recursively */
  2014. int ast_cli_register(struct ast_cli_entry *e)
  2015. {
  2016. return __ast_cli_register(e, NULL);
  2017. }
  2018. /*
  2019. * register/unregister an array of entries.
  2020. */
  2021. int ast_cli_register_multiple(struct ast_cli_entry *e, int len)
  2022. {
  2023. int i, res = 0;
  2024. for (i = 0; i < len; i++)
  2025. res |= ast_cli_register(e + i);
  2026. return res;
  2027. }
  2028. int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
  2029. {
  2030. int i, res = 0;
  2031. for (i = 0; i < len; i++)
  2032. res |= ast_cli_unregister(e + i);
  2033. return res;
  2034. }
  2035. /*! \brief helper for final part of handle_help
  2036. * if locked = 1, assume the list is already locked
  2037. */
  2038. static char *help1(int fd, const char * const match[], int locked)
  2039. {
  2040. char matchstr[80] = "";
  2041. struct ast_cli_entry *e = NULL;
  2042. int len = 0;
  2043. int found = 0;
  2044. if (match) {
  2045. ast_join(matchstr, sizeof(matchstr), match);
  2046. len = strlen(matchstr);
  2047. }
  2048. if (!locked)
  2049. AST_RWLIST_RDLOCK(&helpers);
  2050. while ( (e = cli_next(e)) ) {
  2051. /* Hide commands that start with '_' */
  2052. if (e->_full_cmd[0] == '_')
  2053. continue;
  2054. if (match && strncasecmp(matchstr, e->_full_cmd, len))
  2055. continue;
  2056. ast_cli(fd, "%-30s -- %s\n", e->_full_cmd,
  2057. S_OR(e->summary, "<no description available>"));
  2058. found++;
  2059. }
  2060. if (!locked)
  2061. AST_RWLIST_UNLOCK(&helpers);
  2062. if (!found && matchstr[0])
  2063. ast_cli(fd, "No such command '%s'.\n", matchstr);
  2064. return CLI_SUCCESS;
  2065. }
  2066. static char *handle_help(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2067. {
  2068. char fullcmd[80];
  2069. struct ast_cli_entry *my_e;
  2070. char *res = CLI_SUCCESS;
  2071. if (cmd == CLI_INIT) {
  2072. e->command = "core show help";
  2073. e->usage =
  2074. "Usage: core show help [topic]\n"
  2075. " When called with a topic as an argument, displays usage\n"
  2076. " information on the given command. If called without a\n"
  2077. " topic, it provides a list of commands.\n";
  2078. return NULL;
  2079. } else if (cmd == CLI_GENERATE) {
  2080. /* skip first 14 or 15 chars, "core show help " */
  2081. int l = strlen(a->line);
  2082. if (l > 15) {
  2083. l = 15;
  2084. }
  2085. /* XXX watch out, should stop to the non-generator parts */
  2086. return __ast_cli_generator(a->line + l, a->word, a->n, 0);
  2087. }
  2088. if (a->argc == e->args) {
  2089. return help1(a->fd, NULL, 0);
  2090. }
  2091. AST_RWLIST_RDLOCK(&helpers);
  2092. my_e = find_cli(a->argv + 3, 1); /* try exact match first */
  2093. if (!my_e) {
  2094. res = help1(a->fd, a->argv + 3, 1 /* locked */);
  2095. AST_RWLIST_UNLOCK(&helpers);
  2096. return res;
  2097. }
  2098. if (my_e->usage)
  2099. ast_cli(a->fd, "%s", my_e->usage);
  2100. else {
  2101. ast_join(fullcmd, sizeof(fullcmd), a->argv + 3);
  2102. ast_cli(a->fd, "No help text available for '%s'.\n", fullcmd);
  2103. }
  2104. AST_RWLIST_UNLOCK(&helpers);
  2105. return res;
  2106. }
  2107. static char *parse_args(const char *s, int *argc, const char *argv[], int max, int *trailingwhitespace)
  2108. {
  2109. char *duplicate, *cur;
  2110. int x = 0;
  2111. int quoted = 0;
  2112. int escaped = 0;
  2113. int whitespace = 1;
  2114. int dummy = 0;
  2115. if (trailingwhitespace == NULL)
  2116. trailingwhitespace = &dummy;
  2117. *trailingwhitespace = 0;
  2118. if (s == NULL) /* invalid, though! */
  2119. return NULL;
  2120. /* make a copy to store the parsed string */
  2121. if (!(duplicate = ast_strdup(s)))
  2122. return NULL;
  2123. cur = duplicate;
  2124. /* Remove leading spaces from the command */
  2125. while (isspace(*s)) {
  2126. cur++;
  2127. s++;
  2128. }
  2129. /* scan the original string copying into cur when needed */
  2130. for (; *s ; s++) {
  2131. if (x >= max - 1) {
  2132. ast_log(LOG_WARNING, "Too many arguments, truncating at %s\n", s);
  2133. break;
  2134. }
  2135. if (*s == '"' && !escaped) {
  2136. quoted = !quoted;
  2137. if (quoted && whitespace) {
  2138. /* start a quoted string from previous whitespace: new argument */
  2139. argv[x++] = cur;
  2140. whitespace = 0;
  2141. }
  2142. } else if ((*s == ' ' || *s == '\t') && !(quoted || escaped)) {
  2143. /* If we are not already in whitespace, and not in a quoted string or
  2144. processing an escape sequence, and just entered whitespace, then
  2145. finalize the previous argument and remember that we are in whitespace
  2146. */
  2147. if (!whitespace) {
  2148. *cur++ = '\0';
  2149. whitespace = 1;
  2150. }
  2151. } else if (*s == '\\' && !escaped) {
  2152. escaped = 1;
  2153. } else {
  2154. if (whitespace) {
  2155. /* we leave whitespace, and are not quoted. So it's a new argument */
  2156. argv[x++] = cur;
  2157. whitespace = 0;
  2158. }
  2159. *cur++ = *s;
  2160. escaped = 0;
  2161. }
  2162. }
  2163. /* Null terminate */
  2164. *cur++ = '\0';
  2165. /* XXX put a NULL in the last argument, because some functions that take
  2166. * the array may want a null-terminated array.
  2167. * argc still reflects the number of non-NULL entries.
  2168. */
  2169. argv[x] = NULL;
  2170. *argc = x;
  2171. *trailingwhitespace = whitespace;
  2172. return duplicate;
  2173. }
  2174. /*! \brief Return the number of unique matches for the generator */
  2175. int ast_cli_generatornummatches(const char *text, const char *word)
  2176. {
  2177. int matches = 0, i = 0;
  2178. char *buf = NULL, *oldbuf = NULL;
  2179. while ((buf = ast_cli_generator(text, word, i++))) {
  2180. if (!oldbuf || strcmp(buf,oldbuf))
  2181. matches++;
  2182. if (oldbuf)
  2183. ast_free(oldbuf);
  2184. oldbuf = buf;
  2185. }
  2186. if (oldbuf)
  2187. ast_free(oldbuf);
  2188. return matches;
  2189. }
  2190. static void destroy_match_list(char **match_list, int matches)
  2191. {
  2192. if (match_list) {
  2193. int idx;
  2194. for (idx = 1; idx < matches; ++idx) {
  2195. ast_free(match_list[idx]);
  2196. }
  2197. ast_free(match_list);
  2198. }
  2199. }
  2200. char **ast_cli_completion_matches(const char *text, const char *word)
  2201. {
  2202. char **match_list = NULL, *retstr, *prevstr;
  2203. char **new_list;
  2204. size_t match_list_len, max_equal, which, i;
  2205. int matches = 0;
  2206. /* leave entry 0 free for the longest common substring */
  2207. match_list_len = 1;
  2208. while ((retstr = ast_cli_generator(text, word, matches)) != NULL) {
  2209. if (matches + 1 >= match_list_len) {
  2210. match_list_len <<= 1;
  2211. new_list = ast_realloc(match_list, match_list_len * sizeof(*match_list));
  2212. if (!new_list) {
  2213. destroy_match_list(match_list, matches);
  2214. return NULL;
  2215. }
  2216. match_list = new_list;
  2217. }
  2218. match_list[++matches] = retstr;
  2219. }
  2220. if (!match_list) {
  2221. return match_list; /* NULL */
  2222. }
  2223. /* Find the longest substring that is common to all results
  2224. * (it is a candidate for completion), and store a copy in entry 0.
  2225. */
  2226. prevstr = match_list[1];
  2227. max_equal = strlen(prevstr);
  2228. for (which = 2; which <= matches; which++) {
  2229. for (i = 0; i < max_equal && toupper(prevstr[i]) == toupper(match_list[which][i]); i++)
  2230. continue;
  2231. max_equal = i;
  2232. }
  2233. retstr = ast_malloc(max_equal + 1);
  2234. if (!retstr) {
  2235. destroy_match_list(match_list, matches);
  2236. return NULL;
  2237. }
  2238. ast_copy_string(retstr, match_list[1], max_equal + 1);
  2239. match_list[0] = retstr;
  2240. /* ensure that the array is NULL terminated */
  2241. if (matches + 1 >= match_list_len) {
  2242. new_list = ast_realloc(match_list, (match_list_len + 1) * sizeof(*match_list));
  2243. if (!new_list) {
  2244. ast_free(retstr);
  2245. destroy_match_list(match_list, matches);
  2246. return NULL;
  2247. }
  2248. match_list = new_list;
  2249. }
  2250. match_list[matches + 1] = NULL;
  2251. return match_list;
  2252. }
  2253. /*! \brief returns true if there are more words to match */
  2254. static int more_words (const char * const *dst)
  2255. {
  2256. int i;
  2257. for (i = 0; dst[i]; i++) {
  2258. if (dst[i][0] != '[')
  2259. return -1;
  2260. }
  2261. return 0;
  2262. }
  2263. /*
  2264. * generate the entry at position 'state'
  2265. */
  2266. static char *__ast_cli_generator(const char *text, const char *word, int state, int lock)
  2267. {
  2268. const char *argv[AST_MAX_ARGS];
  2269. struct ast_cli_entry *e = NULL;
  2270. int x = 0, argindex, matchlen;
  2271. int matchnum=0;
  2272. char *ret = NULL;
  2273. char matchstr[80] = "";
  2274. int tws = 0;
  2275. /* Split the argument into an array of words */
  2276. char *duplicate = parse_args(text, &x, argv, ARRAY_LEN(argv), &tws);
  2277. if (!duplicate) /* malloc error */
  2278. return NULL;
  2279. /* Compute the index of the last argument (could be an empty string) */
  2280. argindex = (!ast_strlen_zero(word) && x>0) ? x-1 : x;
  2281. /* rebuild the command, ignore terminating white space and flatten space */
  2282. ast_join(matchstr, sizeof(matchstr)-1, argv);
  2283. matchlen = strlen(matchstr);
  2284. if (tws) {
  2285. strcat(matchstr, " "); /* XXX */
  2286. if (matchlen)
  2287. matchlen++;
  2288. }
  2289. if (lock)
  2290. AST_RWLIST_RDLOCK(&helpers);
  2291. while ( (e = cli_next(e)) ) {
  2292. /* XXX repeated code */
  2293. int src = 0, dst = 0, n = 0;
  2294. if (e->command[0] == '_')
  2295. continue;
  2296. /*
  2297. * Try to match words, up to and excluding the last word, which
  2298. * is either a blank or something that we want to extend.
  2299. */
  2300. for (;src < argindex; dst++, src += n) {
  2301. n = word_match(argv[src], e->cmda[dst]);
  2302. if (n < 0)
  2303. break;
  2304. }
  2305. if (src != argindex && more_words(e->cmda + dst)) /* not a match */
  2306. continue;
  2307. ret = is_prefix(argv[src], e->cmda[dst], state - matchnum, &n);
  2308. matchnum += n; /* this many matches here */
  2309. if (ret) {
  2310. /*
  2311. * argv[src] is a valid prefix of the next word in this
  2312. * command. If this is also the correct entry, return it.
  2313. */
  2314. if (matchnum > state)
  2315. break;
  2316. ast_free(ret);
  2317. ret = NULL;
  2318. } else if (ast_strlen_zero(e->cmda[dst])) {
  2319. /*
  2320. * This entry is a prefix of the command string entered
  2321. * (only one entry in the list should have this property).
  2322. * Run the generator if one is available. In any case we are done.
  2323. */
  2324. if (e->handler) { /* new style command */
  2325. struct ast_cli_args a = {
  2326. .line = matchstr, .word = word,
  2327. .pos = argindex,
  2328. .n = state - matchnum,
  2329. .argv = argv,
  2330. .argc = x};
  2331. ret = e->handler(e, CLI_GENERATE, &a);
  2332. }
  2333. if (ret)
  2334. break;
  2335. }
  2336. }
  2337. if (lock)
  2338. AST_RWLIST_UNLOCK(&helpers);
  2339. ast_free(duplicate);
  2340. return ret;
  2341. }
  2342. char *ast_cli_generator(const char *text, const char *word, int state)
  2343. {
  2344. return __ast_cli_generator(text, word, state, 1);
  2345. }
  2346. int ast_cli_command_full(int uid, int gid, int fd, const char *s)
  2347. {
  2348. const char *args[AST_MAX_ARGS + 1];
  2349. struct ast_cli_entry *e;
  2350. int x;
  2351. char *duplicate = parse_args(s, &x, args + 1, AST_MAX_ARGS, NULL);
  2352. char tmp[AST_MAX_ARGS + 1];
  2353. char *retval = NULL;
  2354. struct ast_cli_args a = {
  2355. .fd = fd, .argc = x, .argv = args+1 };
  2356. if (duplicate == NULL)
  2357. return -1;
  2358. if (x < 1) /* We need at least one entry, otherwise ignore */
  2359. goto done;
  2360. AST_RWLIST_RDLOCK(&helpers);
  2361. e = find_cli(args + 1, 0);
  2362. if (e)
  2363. ast_atomic_fetchadd_int(&e->inuse, 1);
  2364. AST_RWLIST_UNLOCK(&helpers);
  2365. if (e == NULL) {
  2366. ast_cli(fd, "No such command '%s' (type 'core show help %s' for other possible commands)\n", s, find_best(args + 1));
  2367. goto done;
  2368. }
  2369. ast_join(tmp, sizeof(tmp), args + 1);
  2370. /* Check if the user has rights to run this command. */
  2371. if (!cli_has_permissions(uid, gid, tmp)) {
  2372. ast_cli(fd, "You don't have permissions to run '%s' command\n", tmp);
  2373. ast_free(duplicate);
  2374. return 0;
  2375. }
  2376. /*
  2377. * Within the handler, argv[-1] contains a pointer to the ast_cli_entry.
  2378. * Remember that the array returned by parse_args is NULL-terminated.
  2379. */
  2380. args[0] = (char *)e;
  2381. retval = e->handler(e, CLI_HANDLER, &a);
  2382. if (retval == CLI_SHOWUSAGE) {
  2383. ast_cli(fd, "%s", S_OR(e->usage, "Invalid usage, but no usage information available.\n"));
  2384. } else {
  2385. if (retval == CLI_FAILURE)
  2386. ast_cli(fd, "Command '%s' failed.\n", s);
  2387. }
  2388. ast_atomic_fetchadd_int(&e->inuse, -1);
  2389. done:
  2390. ast_free(duplicate);
  2391. return 0;
  2392. }
  2393. int ast_cli_command_multiple_full(int uid, int gid, int fd, size_t size, const char *s)
  2394. {
  2395. char cmd[512];
  2396. int x, y = 0, count = 0;
  2397. for (x = 0; x < size; x++) {
  2398. cmd[y] = s[x];
  2399. y++;
  2400. if (s[x] == '\0') {
  2401. ast_cli_command_full(uid, gid, fd, cmd);
  2402. y = 0;
  2403. count++;
  2404. }
  2405. }
  2406. return count;
  2407. }