cli.c 75 KB

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