cli.c 70 KB

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