cli.c 78 KB

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