control_cmd.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file control_cmd.c
  6. * \brief Implement various commands for Tor's control-socket interface.
  7. **/
  8. #define CONTROL_MODULE_PRIVATE
  9. #define CONTROL_CMD_PRIVATE
  10. #define CONTROL_EVENTS_PRIVATE
  11. #include "core/or/or.h"
  12. #include "app/config/config.h"
  13. #include "lib/confmgt/confparse.h"
  14. #include "app/main/main.h"
  15. #include "core/mainloop/connection.h"
  16. #include "core/or/circuitbuild.h"
  17. #include "core/or/circuitlist.h"
  18. #include "core/or/circuituse.h"
  19. #include "core/or/connection_edge.h"
  20. #include "feature/client/addressmap.h"
  21. #include "feature/client/dnsserv.h"
  22. #include "feature/client/entrynodes.h"
  23. #include "feature/control/control.h"
  24. #include "feature/control/control_auth.h"
  25. #include "feature/control/control_cmd.h"
  26. #include "feature/control/control_events.h"
  27. #include "feature/control/control_getinfo.h"
  28. #include "feature/control/control_proto.h"
  29. #include "feature/hs/hs_control.h"
  30. #include "feature/nodelist/nodelist.h"
  31. #include "feature/nodelist/routerinfo.h"
  32. #include "feature/nodelist/routerlist.h"
  33. #include "feature/rend/rendclient.h"
  34. #include "feature/rend/rendcommon.h"
  35. #include "feature/rend/rendparse.h"
  36. #include "feature/rend/rendservice.h"
  37. #include "lib/crypt_ops/crypto_rand.h"
  38. #include "lib/crypt_ops/crypto_util.h"
  39. #include "lib/encoding/confline.h"
  40. #include "lib/encoding/kvline.h"
  41. #include "core/or/cpath_build_state_st.h"
  42. #include "core/or/entry_connection_st.h"
  43. #include "core/or/origin_circuit_st.h"
  44. #include "core/or/socks_request_st.h"
  45. #include "feature/control/control_cmd_args_st.h"
  46. #include "feature/control/control_connection_st.h"
  47. #include "feature/nodelist/node_st.h"
  48. #include "feature/nodelist/routerinfo_st.h"
  49. #include "feature/rend/rend_authorized_client_st.h"
  50. #include "feature/rend/rend_encoded_v2_service_descriptor_st.h"
  51. #include "feature/rend/rend_service_descriptor_st.h"
  52. static int control_setconf_helper(control_connection_t *conn,
  53. const control_cmd_args_t *args,
  54. int use_defaults);
  55. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  56. * finished authentication and is accepting commands. */
  57. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  58. /**
  59. * Release all storage held in <b>args</b>
  60. **/
  61. void
  62. control_cmd_args_free_(control_cmd_args_t *args)
  63. {
  64. if (! args)
  65. return;
  66. if (args->args) {
  67. SMARTLIST_FOREACH(args->args, char *, c, tor_free(c));
  68. smartlist_free(args->args);
  69. }
  70. config_free_lines(args->kwargs);
  71. tor_free(args->cmddata);
  72. tor_free(args);
  73. }
  74. /** Erase all memory held in <b>args</b>. */
  75. void
  76. control_cmd_args_wipe(control_cmd_args_t *args)
  77. {
  78. if (!args)
  79. return;
  80. if (args->args) {
  81. SMARTLIST_FOREACH(args->args, char *, c, memwipe(c, 0, strlen(c)));
  82. }
  83. for (config_line_t *line = args->kwargs; line; line = line->next) {
  84. memwipe(line->key, 0, strlen(line->key));
  85. memwipe(line->value, 0, strlen(line->value));
  86. }
  87. if (args->cmddata)
  88. memwipe(args->cmddata, 0, args->cmddata_len);
  89. }
  90. /**
  91. * Return true iff any element of the NULL-terminated <b>array</b> matches
  92. * <b>kwd</b>. Case-insensitive.
  93. **/
  94. static bool
  95. string_array_contains_keyword(const char **array, const char *kwd)
  96. {
  97. for (unsigned i = 0; array[i]; ++i) {
  98. if (! strcasecmp(array[i], kwd))
  99. return true;
  100. }
  101. return false;
  102. }
  103. /** Helper for argument parsing: check whether the keyword arguments just
  104. * parsed in <b>result</b> were well-formed according to <b>syntax</b>.
  105. *
  106. * On success, return 0. On failure, return -1 and set *<b>error_out</b>
  107. * to a newly allocated error string.
  108. **/
  109. static int
  110. kvline_check_keyword_args(const control_cmd_args_t *result,
  111. const control_cmd_syntax_t *syntax,
  112. char **error_out)
  113. {
  114. if (result->kwargs == NULL) {
  115. tor_asprintf(error_out, "Cannot parse keyword argument(s)");
  116. return -1;
  117. }
  118. if (! syntax->allowed_keywords) {
  119. /* All keywords are permitted. */
  120. return 0;
  121. }
  122. /* Check for unpermitted arguments */
  123. const config_line_t *line;
  124. for (line = result->kwargs; line; line = line->next) {
  125. if (! string_array_contains_keyword(syntax->allowed_keywords,
  126. line->key)) {
  127. tor_asprintf(error_out, "Unrecognized keyword argument %s",
  128. escaped(line->key));
  129. return -1;
  130. }
  131. }
  132. return 0;
  133. }
  134. /**
  135. * Helper: parse the arguments to a command according to <b>syntax</b>. On
  136. * success, set *<b>error_out</b> to NULL and return a newly allocated
  137. * control_cmd_args_t. On failure, set *<b>error_out</b> to newly allocated
  138. * error string, and return NULL.
  139. **/
  140. STATIC control_cmd_args_t *
  141. control_cmd_parse_args(const char *command,
  142. const control_cmd_syntax_t *syntax,
  143. size_t body_len,
  144. const char *body,
  145. char **error_out)
  146. {
  147. *error_out = NULL;
  148. control_cmd_args_t *result = tor_malloc_zero(sizeof(control_cmd_args_t));
  149. const char *cmdline;
  150. char *cmdline_alloc = NULL;
  151. tor_assert(syntax->max_args < INT_MAX || syntax->max_args == UINT_MAX);
  152. result->command = command;
  153. if (syntax->store_raw_body) {
  154. tor_assert(body[body_len] == 0);
  155. result->raw_body = body;
  156. }
  157. const char *eol = memchr(body, '\n', body_len);
  158. if (syntax->want_cmddata) {
  159. if (! eol || (eol+1) == body+body_len) {
  160. *error_out = tor_strdup("Empty body");
  161. goto err;
  162. }
  163. cmdline_alloc = tor_memdup_nulterm(body, eol-body);
  164. cmdline = cmdline_alloc;
  165. ++eol;
  166. result->cmddata_len = read_escaped_data(eol, (body+body_len)-eol,
  167. &result->cmddata);
  168. } else {
  169. if (eol && (eol+1) != body+body_len) {
  170. *error_out = tor_strdup("Unexpected body");
  171. goto err;
  172. }
  173. cmdline = body;
  174. }
  175. result->args = smartlist_new();
  176. smartlist_split_string(result->args, cmdline, " ",
  177. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK,
  178. (int)(syntax->max_args+1));
  179. size_t n_args = smartlist_len(result->args);
  180. if (n_args < syntax->min_args) {
  181. tor_asprintf(error_out, "Need at least %u argument(s)",
  182. syntax->min_args);
  183. goto err;
  184. } else if (n_args > syntax->max_args && ! syntax->accept_keywords) {
  185. tor_asprintf(error_out, "Cannot accept more than %u argument(s)",
  186. syntax->max_args);
  187. goto err;
  188. }
  189. if (n_args > syntax->max_args) {
  190. /* We have extra arguments after the positional arguments, and we didn't
  191. treat them as an error, so they must count as keyword arguments: Either
  192. K=V pairs, or flags, or both. */
  193. tor_assert(n_args == syntax->max_args + 1);
  194. tor_assert(syntax->accept_keywords);
  195. char *remainder = smartlist_pop_last(result->args);
  196. result->kwargs = kvline_parse(remainder, syntax->kvline_flags);
  197. tor_free(remainder);
  198. if (kvline_check_keyword_args(result, syntax, error_out) < 0) {
  199. goto err;
  200. }
  201. }
  202. tor_assert_nonfatal(*error_out == NULL);
  203. goto done;
  204. err:
  205. tor_assert_nonfatal(*error_out != NULL);
  206. control_cmd_args_free(result);
  207. done:
  208. tor_free(cmdline_alloc);
  209. return result;
  210. }
  211. /**
  212. * Return true iff <b>lines</b> contains <b>flags</b> as a no-value
  213. * (keyword-only) entry.
  214. **/
  215. static bool
  216. config_lines_contain_flag(const config_line_t *lines, const char *flag)
  217. {
  218. const config_line_t *line = config_line_find_case(lines, flag);
  219. return line && !strcmp(line->value, "");
  220. }
  221. static const control_cmd_syntax_t setconf_syntax = {
  222. .max_args=0,
  223. .accept_keywords=true,
  224. .kvline_flags=KV_OMIT_VALS|KV_QUOTED,
  225. };
  226. /** Called when we receive a SETCONF message: parse the body and try
  227. * to update our configuration. Reply with a DONE or ERROR message.
  228. * Modifies the contents of body.*/
  229. static int
  230. handle_control_setconf(control_connection_t *conn,
  231. const control_cmd_args_t *args)
  232. {
  233. return control_setconf_helper(conn, args, 0);
  234. }
  235. static const control_cmd_syntax_t resetconf_syntax = {
  236. .max_args=0,
  237. .accept_keywords=true,
  238. .kvline_flags=KV_OMIT_VALS|KV_QUOTED,
  239. };
  240. /** Called when we receive a RESETCONF message: parse the body and try
  241. * to update our configuration. Reply with a DONE or ERROR message.
  242. * Modifies the contents of body. */
  243. static int
  244. handle_control_resetconf(control_connection_t *conn,
  245. const control_cmd_args_t *args)
  246. {
  247. return control_setconf_helper(conn, args, 1);
  248. }
  249. static const control_cmd_syntax_t getconf_syntax = {
  250. .max_args=UINT_MAX
  251. };
  252. /** Called when we receive a GETCONF message. Parse the request, and
  253. * reply with a CONFVALUE or an ERROR message */
  254. static int
  255. handle_control_getconf(control_connection_t *conn,
  256. const control_cmd_args_t *args)
  257. {
  258. const smartlist_t *questions = args->args;
  259. smartlist_t *answers = smartlist_new();
  260. smartlist_t *unrecognized = smartlist_new();
  261. char *msg = NULL;
  262. size_t msg_len;
  263. const or_options_t *options = get_options();
  264. int i, len;
  265. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  266. if (!option_is_recognized(q)) {
  267. smartlist_add(unrecognized, (char*) q);
  268. } else {
  269. config_line_t *answer = option_get_assignment(options,q);
  270. if (!answer) {
  271. const char *name = option_get_canonical_name(q);
  272. smartlist_add_asprintf(answers, "250-%s\r\n", name);
  273. }
  274. while (answer) {
  275. config_line_t *next;
  276. smartlist_add_asprintf(answers, "250-%s=%s\r\n",
  277. answer->key, answer->value);
  278. next = answer->next;
  279. tor_free(answer->key);
  280. tor_free(answer->value);
  281. tor_free(answer);
  282. answer = next;
  283. }
  284. }
  285. } SMARTLIST_FOREACH_END(q);
  286. if ((len = smartlist_len(unrecognized))) {
  287. for (i=0; i < len-1; ++i)
  288. control_printf_midreply(conn, 552,
  289. "Unrecognized configuration key \"%s\"",
  290. (char*)smartlist_get(unrecognized, i));
  291. control_printf_endreply(conn, 552,
  292. "Unrecognized configuration key \"%s\"",
  293. (char*)smartlist_get(unrecognized, len-1));
  294. } else if ((len = smartlist_len(answers))) {
  295. char *tmp = smartlist_get(answers, len-1);
  296. tor_assert(strlen(tmp)>4);
  297. tmp[3] = ' ';
  298. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  299. connection_buf_add(msg, msg_len, TO_CONN(conn));
  300. } else {
  301. send_control_done(conn);
  302. }
  303. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  304. smartlist_free(answers);
  305. smartlist_free(unrecognized);
  306. tor_free(msg);
  307. return 0;
  308. }
  309. static const control_cmd_syntax_t loadconf_syntax = {
  310. .want_cmddata = true
  311. };
  312. /** Called when we get a +LOADCONF message. */
  313. static int
  314. handle_control_loadconf(control_connection_t *conn,
  315. const control_cmd_args_t *args)
  316. {
  317. setopt_err_t retval;
  318. char *errstring = NULL;
  319. retval = options_init_from_string(NULL, args->cmddata,
  320. CMD_RUN_TOR, NULL, &errstring);
  321. if (retval != SETOPT_OK)
  322. log_warn(LD_CONTROL,
  323. "Controller gave us config file that didn't validate: %s",
  324. errstring);
  325. #define SEND_ERRMSG(code, msg) \
  326. control_printf_endreply(conn, code, msg "%s%s", \
  327. errstring ? ": " : "", \
  328. errstring ? errstring : "")
  329. switch (retval) {
  330. case SETOPT_ERR_PARSE:
  331. SEND_ERRMSG(552, "Invalid config file");
  332. break;
  333. case SETOPT_ERR_TRANSITION:
  334. SEND_ERRMSG(553, "Transition not allowed");
  335. break;
  336. case SETOPT_ERR_SETTING:
  337. SEND_ERRMSG(553, "Unable to set option");
  338. break;
  339. case SETOPT_ERR_MISC:
  340. default:
  341. SEND_ERRMSG(550, "Unable to load config");
  342. break;
  343. case SETOPT_OK:
  344. send_control_done(conn);
  345. break;
  346. }
  347. #undef SEND_ERRMSG
  348. tor_free(errstring);
  349. return 0;
  350. }
  351. static const control_cmd_syntax_t setevents_syntax = {
  352. .max_args = UINT_MAX
  353. };
  354. /** Called when we get a SETEVENTS message: update conn->event_mask,
  355. * and reply with DONE or ERROR. */
  356. static int
  357. handle_control_setevents(control_connection_t *conn,
  358. const control_cmd_args_t *args)
  359. {
  360. int event_code;
  361. event_mask_t event_mask = 0;
  362. const smartlist_t *events = args->args;
  363. SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
  364. {
  365. if (!strcasecmp(ev, "EXTENDED") ||
  366. !strcasecmp(ev, "AUTHDIR_NEWDESCS")) {
  367. log_warn(LD_CONTROL, "The \"%s\" SETEVENTS argument is no longer "
  368. "supported.", ev);
  369. continue;
  370. } else {
  371. int i;
  372. event_code = -1;
  373. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  374. if (!strcasecmp(ev, control_event_table[i].event_name)) {
  375. event_code = control_event_table[i].event_code;
  376. break;
  377. }
  378. }
  379. if (event_code == -1) {
  380. control_printf_endreply(conn, 552, "Unrecognized event \"%s\"", ev);
  381. return 0;
  382. }
  383. }
  384. event_mask |= (((event_mask_t)1) << event_code);
  385. }
  386. SMARTLIST_FOREACH_END(ev);
  387. conn->event_mask = event_mask;
  388. control_update_global_event_mask();
  389. send_control_done(conn);
  390. return 0;
  391. }
  392. static const control_cmd_syntax_t saveconf_syntax = {
  393. .max_args = 0,
  394. .accept_keywords = true,
  395. .kvline_flags=KV_OMIT_VALS,
  396. };
  397. /** Called when we get a SAVECONF command. Try to flush the current options to
  398. * disk, and report success or failure. */
  399. static int
  400. handle_control_saveconf(control_connection_t *conn,
  401. const control_cmd_args_t *args)
  402. {
  403. bool force = config_lines_contain_flag(args->kwargs, "FORCE");
  404. const or_options_t *options = get_options();
  405. if ((!force && options->IncludeUsed) || options_save_current() < 0) {
  406. control_write_endreply(conn, 551,
  407. "Unable to write configuration to disk.");
  408. } else {
  409. send_control_done(conn);
  410. }
  411. return 0;
  412. }
  413. static const control_cmd_syntax_t signal_syntax = {
  414. .min_args = 1,
  415. .max_args = 1,
  416. };
  417. /** Called when we get a SIGNAL command. React to the provided signal, and
  418. * report success or failure. (If the signal results in a shutdown, success
  419. * may not be reported.) */
  420. static int
  421. handle_control_signal(control_connection_t *conn,
  422. const control_cmd_args_t *args)
  423. {
  424. int sig = -1;
  425. int i;
  426. tor_assert(smartlist_len(args->args) == 1);
  427. const char *s = smartlist_get(args->args, 0);
  428. for (i = 0; signal_table[i].signal_name != NULL; ++i) {
  429. if (!strcasecmp(s, signal_table[i].signal_name)) {
  430. sig = signal_table[i].sig;
  431. break;
  432. }
  433. }
  434. if (sig < 0)
  435. control_printf_endreply(conn, 552, "Unrecognized signal code \"%s\"", s);
  436. if (sig < 0)
  437. return 0;
  438. send_control_done(conn);
  439. /* Flush the "done" first if the signal might make us shut down. */
  440. if (sig == SIGTERM || sig == SIGINT)
  441. connection_flush(TO_CONN(conn));
  442. activate_signal(sig);
  443. return 0;
  444. }
  445. static const control_cmd_syntax_t takeownership_syntax = {
  446. .max_args = UINT_MAX, // This should probably become zero. XXXXX
  447. };
  448. /** Called when we get a TAKEOWNERSHIP command. Mark this connection
  449. * as an owning connection, so that we will exit if the connection
  450. * closes. */
  451. static int
  452. handle_control_takeownership(control_connection_t *conn,
  453. const control_cmd_args_t *args)
  454. {
  455. (void)args;
  456. conn->is_owning_control_connection = 1;
  457. log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
  458. "Tor instance.",
  459. (int)(conn->base_.s));
  460. send_control_done(conn);
  461. return 0;
  462. }
  463. static const control_cmd_syntax_t dropownership_syntax = {
  464. .max_args = UINT_MAX, // This should probably become zero. XXXXX
  465. };
  466. /** Called when we get a DROPOWNERSHIP command. Mark this connection
  467. * as a non-owning connection, so that we will not exit if the connection
  468. * closes. */
  469. static int
  470. handle_control_dropownership(control_connection_t *conn,
  471. const control_cmd_args_t *args)
  472. {
  473. (void)args;
  474. conn->is_owning_control_connection = 0;
  475. log_info(LD_CONTROL, "Control connection %d has dropped ownership of this "
  476. "Tor instance.",
  477. (int)(conn->base_.s));
  478. send_control_done(conn);
  479. return 0;
  480. }
  481. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  482. static origin_circuit_t *
  483. get_circ(const char *id)
  484. {
  485. uint32_t n_id;
  486. int ok;
  487. n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  488. if (!ok)
  489. return NULL;
  490. return circuit_get_by_global_id(n_id);
  491. }
  492. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  493. static entry_connection_t *
  494. get_stream(const char *id)
  495. {
  496. uint64_t n_id;
  497. int ok;
  498. connection_t *conn;
  499. n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  500. if (!ok)
  501. return NULL;
  502. conn = connection_get_by_global_id(n_id);
  503. if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
  504. return NULL;
  505. return TO_ENTRY_CONN(conn);
  506. }
  507. /** Helper for setconf and resetconf. Acts like setconf, except
  508. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  509. * contents of body.
  510. */
  511. static int
  512. control_setconf_helper(control_connection_t *conn,
  513. const control_cmd_args_t *args,
  514. int use_defaults)
  515. {
  516. setopt_err_t opt_err;
  517. char *errstring = NULL;
  518. const unsigned flags =
  519. CAL_CLEAR_FIRST | (use_defaults ? CAL_USE_DEFAULTS : 0);
  520. // We need a copy here, since confparse.c wants to canonicalize cases.
  521. config_line_t *lines = config_lines_dup(args->kwargs);
  522. opt_err = options_trial_assign(lines, flags, &errstring);
  523. {
  524. #define SEND_ERRMSG(code, msg) \
  525. control_printf_endreply(conn, code, msg ": %s", errstring);
  526. switch (opt_err) {
  527. case SETOPT_ERR_MISC:
  528. SEND_ERRMSG(552, "Unrecognized option");
  529. break;
  530. case SETOPT_ERR_PARSE:
  531. SEND_ERRMSG(513, "Unacceptable option value");
  532. break;
  533. case SETOPT_ERR_TRANSITION:
  534. SEND_ERRMSG(553, "Transition not allowed");
  535. break;
  536. case SETOPT_ERR_SETTING:
  537. default:
  538. SEND_ERRMSG(553, "Unable to set option");
  539. break;
  540. case SETOPT_OK:
  541. config_free_lines(lines);
  542. send_control_done(conn);
  543. return 0;
  544. }
  545. #undef SEND_ERRMSG
  546. log_warn(LD_CONTROL,
  547. "Controller gave us config lines that didn't validate: %s",
  548. errstring);
  549. config_free_lines(lines);
  550. tor_free(errstring);
  551. return 0;
  552. }
  553. }
  554. /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
  555. * containing funny characters. */
  556. static int
  557. address_is_invalid_mapaddress_target(const char *addr)
  558. {
  559. if (!strcmpstart(addr, "*."))
  560. return address_is_invalid_destination(addr+2, 1);
  561. else
  562. return address_is_invalid_destination(addr, 1);
  563. }
  564. static const control_cmd_syntax_t mapaddress_syntax = {
  565. .max_args=1,
  566. .accept_keywords=true,
  567. };
  568. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  569. * and report success or failure. */
  570. static int
  571. handle_control_mapaddress(control_connection_t *conn,
  572. const control_cmd_args_t *args)
  573. {
  574. smartlist_t *reply;
  575. char *r;
  576. size_t sz;
  577. reply = smartlist_new();
  578. const config_line_t *line;
  579. for (line = args->kwargs; line; line = line->next) {
  580. const char *from = line->key;
  581. const char *to = line->value;
  582. {
  583. if (address_is_invalid_mapaddress_target(to)) {
  584. smartlist_add_asprintf(reply,
  585. "512-syntax error: invalid address '%s'", to);
  586. log_warn(LD_CONTROL,
  587. "Skipping invalid argument '%s' in MapAddress msg", to);
  588. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
  589. !strcmp(from, "::")) {
  590. const char type =
  591. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
  592. (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
  593. const char *address = addressmap_register_virtual_address(
  594. type, tor_strdup(to));
  595. if (!address) {
  596. smartlist_add_asprintf(reply,
  597. "451-resource exhausted: skipping '%s=%s'", from,to);
  598. log_warn(LD_CONTROL,
  599. "Unable to allocate address for '%s' in MapAddress msg",
  600. safe_str_client(to));
  601. } else {
  602. smartlist_add_asprintf(reply, "250-%s=%s", address, to);
  603. }
  604. } else {
  605. const char *msg;
  606. if (addressmap_register_auto(from, to, 1,
  607. ADDRMAPSRC_CONTROLLER, &msg) < 0) {
  608. smartlist_add_asprintf(reply,
  609. "512-syntax error: invalid address mapping "
  610. " '%s=%s': %s", from, to, msg);
  611. log_warn(LD_CONTROL,
  612. "Skipping invalid argument '%s=%s' in MapAddress msg: %s",
  613. from, to, msg);
  614. } else {
  615. smartlist_add_asprintf(reply, "250-%s=%s", from, to);
  616. }
  617. }
  618. }
  619. }
  620. if (smartlist_len(reply)) {
  621. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  622. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  623. connection_buf_add(r, sz, TO_CONN(conn));
  624. tor_free(r);
  625. } else {
  626. control_write_endreply(conn, 512, "syntax error: "
  627. "not enough arguments to mapaddress.");
  628. }
  629. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  630. smartlist_free(reply);
  631. return 0;
  632. }
  633. /** Given a string, convert it to a circuit purpose. */
  634. static uint8_t
  635. circuit_purpose_from_string(const char *string)
  636. {
  637. if (!strcasecmpstart(string, "purpose="))
  638. string += strlen("purpose=");
  639. if (!strcasecmp(string, "general"))
  640. return CIRCUIT_PURPOSE_C_GENERAL;
  641. else if (!strcasecmp(string, "controller"))
  642. return CIRCUIT_PURPOSE_CONTROLLER;
  643. else
  644. return CIRCUIT_PURPOSE_UNKNOWN;
  645. }
  646. static const control_cmd_syntax_t extendcircuit_syntax = {
  647. .min_args=1,
  648. .max_args=1, // see note in function
  649. .accept_keywords=true,
  650. .kvline_flags=KV_OMIT_VALS
  651. };
  652. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  653. * circuit, and report success or failure. */
  654. static int
  655. handle_control_extendcircuit(control_connection_t *conn,
  656. const control_cmd_args_t *args)
  657. {
  658. smartlist_t *router_nicknames=smartlist_new(), *nodes=NULL;
  659. origin_circuit_t *circ = NULL;
  660. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  661. const config_line_t *kwargs = args->kwargs;
  662. const char *circ_id = smartlist_get(args->args, 0);
  663. const char *path_str = NULL;
  664. char *path_str_alloc = NULL;
  665. /* The syntax for this command is unfortunate. The second argument is
  666. optional, and is a comma-separated list long-format fingerprints, which
  667. can (historically!) contain an equals sign.
  668. Here we check the second argument to see if it's a path, and if so we
  669. remove it from the kwargs list and put it in path_str.
  670. */
  671. if (kwargs) {
  672. const config_line_t *arg1 = kwargs;
  673. if (!strcmp(arg1->value, "")) {
  674. path_str = arg1->key;
  675. kwargs = kwargs->next;
  676. } else if (arg1->key[0] == '$') {
  677. tor_asprintf(&path_str_alloc, "%s=%s", arg1->key, arg1->value);
  678. path_str = path_str_alloc;
  679. kwargs = kwargs->next;
  680. }
  681. }
  682. const config_line_t *purpose_line = config_line_find_case(kwargs, "PURPOSE");
  683. bool zero_circ = !strcmp("0", circ_id);
  684. if (purpose_line) {
  685. intended_purpose = circuit_purpose_from_string(purpose_line->value);
  686. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  687. control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
  688. purpose_line->value);
  689. goto done;
  690. }
  691. }
  692. if (zero_circ) {
  693. if (!path_str) {
  694. // "EXTENDCIRCUIT 0" with no path.
  695. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  696. if (!circ) {
  697. control_write_endreply(conn, 551, "Couldn't start circuit");
  698. } else {
  699. control_printf_endreply(conn, 250, "EXTENDED %lu",
  700. (unsigned long)circ->global_identifier);
  701. }
  702. goto done;
  703. }
  704. }
  705. if (!zero_circ && !(circ = get_circ(circ_id))) {
  706. control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
  707. goto done;
  708. }
  709. if (!path_str) {
  710. control_write_endreply(conn, 512, "syntax error: path required.");
  711. goto done;
  712. }
  713. smartlist_split_string(router_nicknames, path_str, ",", 0, 0);
  714. nodes = smartlist_new();
  715. bool first_node = zero_circ;
  716. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  717. const node_t *node = node_get_by_nickname(n, 0);
  718. if (!node) {
  719. control_printf_endreply(conn, 552, "No such router \"%s\"", n);
  720. goto done;
  721. }
  722. if (!node_has_preferred_descriptor(node, first_node)) {
  723. control_printf_endreply(conn, 552, "No descriptor for \"%s\"", n);
  724. goto done;
  725. }
  726. smartlist_add(nodes, (void*)node);
  727. first_node = false;
  728. } SMARTLIST_FOREACH_END(n);
  729. if (!smartlist_len(nodes)) {
  730. control_write_endreply(conn, 512, "No router names provided");
  731. goto done;
  732. }
  733. if (zero_circ) {
  734. /* start a new circuit */
  735. circ = origin_circuit_init(intended_purpose, 0);
  736. }
  737. /* now circ refers to something that is ready to be extended */
  738. first_node = zero_circ;
  739. SMARTLIST_FOREACH(nodes, const node_t *, node,
  740. {
  741. extend_info_t *info = extend_info_from_node(node, first_node);
  742. if (!info) {
  743. tor_assert_nonfatal(first_node);
  744. log_warn(LD_CONTROL,
  745. "controller tried to connect to a node that lacks a suitable "
  746. "descriptor, or which doesn't have any "
  747. "addresses that are allowed by the firewall configuration; "
  748. "circuit marked for closing.");
  749. circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
  750. control_write_endreply(conn, 551, "Couldn't start circuit");
  751. goto done;
  752. }
  753. circuit_append_new_exit(circ, info);
  754. if (circ->build_state->desired_path_len > 1) {
  755. circ->build_state->onehop_tunnel = 0;
  756. }
  757. extend_info_free(info);
  758. first_node = 0;
  759. });
  760. /* now that we've populated the cpath, start extending */
  761. if (zero_circ) {
  762. int err_reason = 0;
  763. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  764. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  765. control_write_endreply(conn, 551, "Couldn't start circuit");
  766. goto done;
  767. }
  768. } else {
  769. if (circ->base_.state == CIRCUIT_STATE_OPEN ||
  770. circ->base_.state == CIRCUIT_STATE_GUARD_WAIT) {
  771. int err_reason = 0;
  772. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  773. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  774. log_info(LD_CONTROL,
  775. "send_next_onion_skin failed; circuit marked for closing.");
  776. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  777. control_write_endreply(conn, 551, "Couldn't send onion skin");
  778. goto done;
  779. }
  780. }
  781. }
  782. control_printf_endreply(conn, 250, "EXTENDED %lu",
  783. (unsigned long)circ->global_identifier);
  784. if (zero_circ) /* send a 'launched' event, for completeness */
  785. circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
  786. done:
  787. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  788. smartlist_free(router_nicknames);
  789. smartlist_free(nodes);
  790. tor_free(path_str_alloc);
  791. return 0;
  792. }
  793. static const control_cmd_syntax_t setcircuitpurpose_syntax = {
  794. .max_args=1,
  795. .accept_keywords=true,
  796. };
  797. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  798. * circuit and it's a valid purpose, change it. */
  799. static int
  800. handle_control_setcircuitpurpose(control_connection_t *conn,
  801. const control_cmd_args_t *args)
  802. {
  803. origin_circuit_t *circ = NULL;
  804. uint8_t new_purpose;
  805. const char *circ_id = smartlist_get(args->args,0);
  806. if (!(circ = get_circ(circ_id))) {
  807. control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
  808. goto done;
  809. }
  810. {
  811. const config_line_t *purp = config_line_find_case(args->kwargs, "PURPOSE");
  812. if (!purp) {
  813. control_write_endreply(conn, 552, "No purpose given");
  814. goto done;
  815. }
  816. new_purpose = circuit_purpose_from_string(purp->value);
  817. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  818. control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
  819. purp->value);
  820. goto done;
  821. }
  822. }
  823. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  824. send_control_done(conn);
  825. done:
  826. return 0;
  827. }
  828. static const char *attachstream_keywords[] = {
  829. "HOP", NULL
  830. };
  831. static const control_cmd_syntax_t attachstream_syntax = {
  832. .min_args=2, .max_args=2,
  833. .accept_keywords=true,
  834. .allowed_keywords=attachstream_keywords
  835. };
  836. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  837. * stream, and report success or failure. */
  838. static int
  839. handle_control_attachstream(control_connection_t *conn,
  840. const control_cmd_args_t *args)
  841. {
  842. entry_connection_t *ap_conn = NULL;
  843. origin_circuit_t *circ = NULL;
  844. crypt_path_t *cpath=NULL;
  845. int hop=0, hop_line_ok=1;
  846. const char *stream_id = smartlist_get(args->args, 0);
  847. const char *circ_id = smartlist_get(args->args, 1);
  848. int zero_circ = !strcmp(circ_id, "0");
  849. const config_line_t *hoparg = config_line_find_case(args->kwargs, "HOP");
  850. if (!(ap_conn = get_stream(stream_id))) {
  851. control_printf_endreply(conn, 552, "Unknown stream \"%s\"", stream_id);
  852. return 0;
  853. } else if (!zero_circ && !(circ = get_circ(circ_id))) {
  854. control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
  855. return 0;
  856. } else if (circ) {
  857. if (hoparg) {
  858. hop = (int) tor_parse_ulong(hoparg->value, 10, 0, INT_MAX,
  859. &hop_line_ok, NULL);
  860. if (!hop_line_ok) { /* broken hop line */
  861. control_printf_endreply(conn, 552, "Bad value hop=%s",
  862. hoparg->value);
  863. return 0;
  864. }
  865. }
  866. }
  867. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  868. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  869. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  870. control_write_endreply(conn, 555,
  871. "Connection is not managed by controller.");
  872. return 0;
  873. }
  874. /* Do we need to detach it first? */
  875. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  876. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  877. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  878. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  879. /* Un-mark it as ending, since we're going to reuse it. */
  880. edge_conn->edge_has_sent_end = 0;
  881. edge_conn->end_reason = 0;
  882. if (tmpcirc)
  883. circuit_detach_stream(tmpcirc, edge_conn);
  884. CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
  885. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  886. }
  887. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  888. control_write_endreply(conn, 551,
  889. "Can't attach stream to non-open origin circuit");
  890. return 0;
  891. }
  892. /* Is this a single hop circuit? */
  893. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  894. control_write_endreply(conn, 551,
  895. "Can't attach stream to this one-hop circuit.");
  896. return 0;
  897. }
  898. if (circ && hop>0) {
  899. /* find this hop in the circuit, and set cpath */
  900. cpath = circuit_get_cpath_hop(circ, hop);
  901. if (!cpath) {
  902. control_printf_endreply(conn, 551, "Circuit doesn't have %d hops.", hop);
  903. return 0;
  904. }
  905. }
  906. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  907. control_write_endreply(conn, 551, "Unable to attach stream");
  908. return 0;
  909. }
  910. send_control_done(conn);
  911. return 0;
  912. }
  913. static const char *postdescriptor_keywords[] = {
  914. "cache", "purpose", NULL,
  915. };
  916. static const control_cmd_syntax_t postdescriptor_syntax = {
  917. .max_args = 0,
  918. .accept_keywords = true,
  919. .allowed_keywords = postdescriptor_keywords,
  920. .want_cmddata = true,
  921. };
  922. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  923. * descriptor, and report success or failure. */
  924. static int
  925. handle_control_postdescriptor(control_connection_t *conn,
  926. const control_cmd_args_t *args)
  927. {
  928. const char *msg=NULL;
  929. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  930. int cache = 0; /* eventually, we may switch this to 1 */
  931. const config_line_t *line;
  932. line = config_line_find_case(args->kwargs, "purpose");
  933. if (line) {
  934. purpose = router_purpose_from_string(line->value);
  935. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  936. control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
  937. line->value);
  938. goto done;
  939. }
  940. }
  941. line = config_line_find_case(args->kwargs, "cache");
  942. if (line) {
  943. if (!strcasecmp(line->value, "no"))
  944. cache = 0;
  945. else if (!strcasecmp(line->value, "yes"))
  946. cache = 1;
  947. else {
  948. control_printf_endreply(conn, 552, "Unknown cache request \"%s\"",
  949. line->value);
  950. goto done;
  951. }
  952. }
  953. switch (router_load_single_router(args->cmddata, purpose, cache, &msg)) {
  954. case -1:
  955. if (!msg) msg = "Could not parse descriptor";
  956. control_write_endreply(conn, 554, msg);
  957. break;
  958. case 0:
  959. if (!msg) msg = "Descriptor not added";
  960. control_write_endreply(conn, 251, msg);
  961. break;
  962. case 1:
  963. send_control_done(conn);
  964. break;
  965. }
  966. done:
  967. return 0;
  968. }
  969. static const control_cmd_syntax_t redirectstream_syntax = {
  970. .min_args = 2,
  971. .max_args = UINT_MAX, // XXX should be 3.
  972. };
  973. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  974. * address of the named AP stream, and report success or failure. */
  975. static int
  976. handle_control_redirectstream(control_connection_t *conn,
  977. const control_cmd_args_t *cmd_args)
  978. {
  979. entry_connection_t *ap_conn = NULL;
  980. char *new_addr = NULL;
  981. uint16_t new_port = 0;
  982. const smartlist_t *args = cmd_args->args;
  983. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  984. || !ap_conn->socks_request) {
  985. control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
  986. (char*)smartlist_get(args, 0));
  987. } else {
  988. int ok = 1;
  989. if (smartlist_len(args) > 2) { /* they included a port too */
  990. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  991. 10, 1, 65535, &ok, NULL);
  992. }
  993. if (!ok) {
  994. control_printf_endreply(conn, 512, "Cannot parse port \"%s\"",
  995. (char*)smartlist_get(args, 2));
  996. } else {
  997. new_addr = tor_strdup(smartlist_get(args, 1));
  998. }
  999. }
  1000. if (!new_addr)
  1001. return 0;
  1002. strlcpy(ap_conn->socks_request->address, new_addr,
  1003. sizeof(ap_conn->socks_request->address));
  1004. if (new_port)
  1005. ap_conn->socks_request->port = new_port;
  1006. tor_free(new_addr);
  1007. send_control_done(conn);
  1008. return 0;
  1009. }
  1010. static const control_cmd_syntax_t closestream_syntax = {
  1011. .min_args = 2,
  1012. .max_args = UINT_MAX, /* XXXX This is the original behavior, but
  1013. * maybe we should change the spec. */
  1014. };
  1015. /** Called when we get a CLOSESTREAM command; try to close the named stream
  1016. * and report success or failure. */
  1017. static int
  1018. handle_control_closestream(control_connection_t *conn,
  1019. const control_cmd_args_t *cmd_args)
  1020. {
  1021. entry_connection_t *ap_conn=NULL;
  1022. uint8_t reason=0;
  1023. int ok;
  1024. const smartlist_t *args = cmd_args->args;
  1025. tor_assert(smartlist_len(args) >= 2);
  1026. if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  1027. control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
  1028. (char*)smartlist_get(args, 0));
  1029. else {
  1030. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  1031. &ok, NULL);
  1032. if (!ok) {
  1033. control_printf_endreply(conn, 552, "Unrecognized reason \"%s\"",
  1034. (char*)smartlist_get(args, 1));
  1035. ap_conn = NULL;
  1036. }
  1037. }
  1038. if (!ap_conn)
  1039. return 0;
  1040. connection_mark_unattached_ap(ap_conn, reason);
  1041. send_control_done(conn);
  1042. return 0;
  1043. }
  1044. static const control_cmd_syntax_t closecircuit_syntax = {
  1045. .min_args=1, .max_args=1,
  1046. .accept_keywords=true,
  1047. .kvline_flags=KV_OMIT_VALS,
  1048. // XXXX we might want to exclude unrecognized flags, but for now we
  1049. // XXXX just ignore them for backward compatibility.
  1050. };
  1051. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  1052. * and report success or failure. */
  1053. static int
  1054. handle_control_closecircuit(control_connection_t *conn,
  1055. const control_cmd_args_t *args)
  1056. {
  1057. const char *circ_id = smartlist_get(args->args, 0);
  1058. origin_circuit_t *circ = NULL;
  1059. if (!(circ=get_circ(circ_id))) {
  1060. control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
  1061. return 0;
  1062. }
  1063. bool safe = config_lines_contain_flag(args->kwargs, "IfUnused");
  1064. if (!safe || !circ->p_streams) {
  1065. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  1066. }
  1067. send_control_done(conn);
  1068. return 0;
  1069. }
  1070. static const control_cmd_syntax_t resolve_syntax = {
  1071. .max_args=0,
  1072. .accept_keywords=true,
  1073. .kvline_flags=KV_OMIT_VALS,
  1074. };
  1075. /** Called when we get a RESOLVE command: start trying to resolve
  1076. * the listed addresses. */
  1077. static int
  1078. handle_control_resolve(control_connection_t *conn,
  1079. const control_cmd_args_t *args)
  1080. {
  1081. smartlist_t *failed;
  1082. int is_reverse = 0;
  1083. if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
  1084. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  1085. "isn't listening for ADDRMAP events. It probably won't see "
  1086. "the answer.");
  1087. }
  1088. {
  1089. const config_line_t *modearg = config_line_find_case(args->kwargs, "mode");
  1090. if (modearg && !strcasecmp(modearg->value, "reverse"))
  1091. is_reverse = 1;
  1092. }
  1093. failed = smartlist_new();
  1094. for (const config_line_t *line = args->kwargs; line; line = line->next) {
  1095. if (!strlen(line->value)) {
  1096. const char *addr = line->key;
  1097. if (dnsserv_launch_request(addr, is_reverse, conn)<0)
  1098. smartlist_add(failed, (char*)addr);
  1099. } else {
  1100. // XXXX arguably we should reject unrecognized keyword arguments,
  1101. // XXXX but the old implementation didn't do that.
  1102. }
  1103. }
  1104. send_control_done(conn);
  1105. SMARTLIST_FOREACH(failed, const char *, arg, {
  1106. control_event_address_mapped(arg, arg, time(NULL),
  1107. "internal", 0);
  1108. });
  1109. smartlist_free(failed);
  1110. return 0;
  1111. }
  1112. static const control_cmd_syntax_t protocolinfo_syntax = {
  1113. .max_args = UINT_MAX
  1114. };
  1115. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  1116. static int
  1117. handle_control_protocolinfo(control_connection_t *conn,
  1118. const control_cmd_args_t *cmd_args)
  1119. {
  1120. const char *bad_arg = NULL;
  1121. const smartlist_t *args = cmd_args->args;
  1122. conn->have_sent_protocolinfo = 1;
  1123. SMARTLIST_FOREACH(args, const char *, arg, {
  1124. int ok;
  1125. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  1126. if (!ok) {
  1127. bad_arg = arg;
  1128. break;
  1129. }
  1130. });
  1131. if (bad_arg) {
  1132. control_printf_endreply(conn, 513, "No such version %s",
  1133. escaped(bad_arg));
  1134. /* Don't tolerate bad arguments when not authenticated. */
  1135. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  1136. connection_mark_for_close(TO_CONN(conn));
  1137. goto done;
  1138. } else {
  1139. const or_options_t *options = get_options();
  1140. int cookies = options->CookieAuthentication;
  1141. char *cfile = get_controller_cookie_file_name();
  1142. char *abs_cfile;
  1143. char *esc_cfile;
  1144. char *methods;
  1145. abs_cfile = make_path_absolute(cfile);
  1146. esc_cfile = esc_for_log(abs_cfile);
  1147. {
  1148. int passwd = (options->HashedControlPassword != NULL ||
  1149. options->HashedControlSessionPassword != NULL);
  1150. smartlist_t *mlist = smartlist_new();
  1151. if (cookies) {
  1152. smartlist_add(mlist, (char*)"COOKIE");
  1153. smartlist_add(mlist, (char*)"SAFECOOKIE");
  1154. }
  1155. if (passwd)
  1156. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  1157. if (!cookies && !passwd)
  1158. smartlist_add(mlist, (char*)"NULL");
  1159. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  1160. smartlist_free(mlist);
  1161. }
  1162. control_write_midreply(conn, 250, "PROTOCOLINFO 1");
  1163. control_printf_midreply(conn, 250, "AUTH METHODS=%s%s%s", methods,
  1164. cookies?" COOKIEFILE=":"",
  1165. cookies?esc_cfile:"");
  1166. control_printf_midreply(conn, 250, "VERSION Tor=%s", escaped(VERSION));
  1167. send_control_done(conn);
  1168. tor_free(methods);
  1169. tor_free(cfile);
  1170. tor_free(abs_cfile);
  1171. tor_free(esc_cfile);
  1172. }
  1173. done:
  1174. return 0;
  1175. }
  1176. static const control_cmd_syntax_t usefeature_syntax = {
  1177. .max_args = UINT_MAX
  1178. };
  1179. /** Called when we get a USEFEATURE command: parse the feature list, and
  1180. * set up the control_connection's options properly. */
  1181. static int
  1182. handle_control_usefeature(control_connection_t *conn,
  1183. const control_cmd_args_t *cmd_args)
  1184. {
  1185. const smartlist_t *args = cmd_args->args;
  1186. int bad = 0;
  1187. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  1188. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  1189. ;
  1190. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  1191. ;
  1192. else {
  1193. control_printf_endreply(conn, 552, "Unrecognized feature \"%s\"",
  1194. arg);
  1195. bad = 1;
  1196. break;
  1197. }
  1198. } SMARTLIST_FOREACH_END(arg);
  1199. if (!bad) {
  1200. send_control_done(conn);
  1201. }
  1202. return 0;
  1203. }
  1204. static const control_cmd_syntax_t dropguards_syntax = {
  1205. .max_args = 0,
  1206. };
  1207. /** Implementation for the DROPGUARDS command. */
  1208. static int
  1209. handle_control_dropguards(control_connection_t *conn,
  1210. const control_cmd_args_t *args)
  1211. {
  1212. (void) args; /* We don't take arguments. */
  1213. static int have_warned = 0;
  1214. if (! have_warned) {
  1215. log_warn(LD_CONTROL, "DROPGUARDS is dangerous; make sure you understand "
  1216. "the risks before using it. It may be removed in a future "
  1217. "version of Tor.");
  1218. have_warned = 1;
  1219. }
  1220. remove_all_entry_guards();
  1221. send_control_done(conn);
  1222. return 0;
  1223. }
  1224. static const char *hsfetch_keywords[] = {
  1225. "SERVER", NULL,
  1226. };
  1227. static const control_cmd_syntax_t hsfetch_syntax = {
  1228. .min_args = 1, .max_args = 1,
  1229. .accept_keywords = true,
  1230. .allowed_keywords = hsfetch_keywords,
  1231. };
  1232. /** Implementation for the HSFETCH command. */
  1233. static int
  1234. handle_control_hsfetch(control_connection_t *conn,
  1235. const control_cmd_args_t *args)
  1236. {
  1237. char digest[DIGEST_LEN], *desc_id = NULL;
  1238. smartlist_t *hsdirs = NULL;
  1239. static const char *v2_str = "v2-";
  1240. const size_t v2_str_len = strlen(v2_str);
  1241. rend_data_t *rend_query = NULL;
  1242. ed25519_public_key_t v3_pk;
  1243. uint32_t version;
  1244. const char *hsaddress = NULL;
  1245. /* Extract the first argument (either HSAddress or DescID). */
  1246. const char *arg1 = smartlist_get(args->args, 0);
  1247. /* Test if it's an HS address without the .onion part. */
  1248. if (rend_valid_v2_service_id(arg1)) {
  1249. hsaddress = arg1;
  1250. version = HS_VERSION_TWO;
  1251. } else if (strcmpstart(arg1, v2_str) == 0 &&
  1252. rend_valid_descriptor_id(arg1 + v2_str_len) &&
  1253. base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
  1254. REND_DESC_ID_V2_LEN_BASE32) ==
  1255. REND_DESC_ID_V2_LEN_BASE32) {
  1256. /* We have a well formed version 2 descriptor ID. Keep the decoded value
  1257. * of the id. */
  1258. desc_id = digest;
  1259. version = HS_VERSION_TWO;
  1260. } else if (hs_address_is_valid(arg1)) {
  1261. hsaddress = arg1;
  1262. version = HS_VERSION_THREE;
  1263. hs_parse_address(hsaddress, &v3_pk, NULL, NULL);
  1264. } else {
  1265. control_printf_endreply(conn, 513, "Invalid argument \"%s\"", arg1);
  1266. goto done;
  1267. }
  1268. for (const config_line_t *line = args->kwargs; line; line = line->next) {
  1269. if (!strcasecmp(line->key, "SERVER")) {
  1270. const char *server = line->value;
  1271. const node_t *node = node_get_by_hex_id(server, 0);
  1272. if (!node) {
  1273. control_printf_endreply(conn, 552, "Server \"%s\" not found", server);
  1274. goto done;
  1275. }
  1276. if (!hsdirs) {
  1277. /* Stores routerstatus_t cmddata for each specified server. */
  1278. hsdirs = smartlist_new();
  1279. }
  1280. /* Valid server, add it to our local list. */
  1281. smartlist_add(hsdirs, node->rs);
  1282. } else {
  1283. tor_assert_nonfatal_unreached();
  1284. }
  1285. }
  1286. if (version == HS_VERSION_TWO) {
  1287. rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
  1288. REND_NO_AUTH);
  1289. if (rend_query == NULL) {
  1290. control_write_endreply(conn, 551, "Error creating the HS query");
  1291. goto done;
  1292. }
  1293. }
  1294. /* Using a descriptor ID, we force the user to provide at least one
  1295. * hsdir server using the SERVER= option. */
  1296. if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
  1297. control_write_endreply(conn, 512, "SERVER option is required");
  1298. goto done;
  1299. }
  1300. /* We are about to trigger HSDir fetch so send the OK now because after
  1301. * that 650 event(s) are possible so better to have the 250 OK before them
  1302. * to avoid out of order replies. */
  1303. send_control_done(conn);
  1304. /* Trigger the fetch using the built rend query and possibly a list of HS
  1305. * directory to use. This function ignores the client cache thus this will
  1306. * always send a fetch command. */
  1307. if (version == HS_VERSION_TWO) {
  1308. rend_client_fetch_v2_desc(rend_query, hsdirs);
  1309. } else if (version == HS_VERSION_THREE) {
  1310. hs_control_hsfetch_command(&v3_pk, hsdirs);
  1311. }
  1312. done:
  1313. /* Contains data pointer that we don't own thus no cleanup. */
  1314. smartlist_free(hsdirs);
  1315. rend_data_free(rend_query);
  1316. return 0;
  1317. }
  1318. static const char *hspost_keywords[] = {
  1319. "SERVER", "HSADDRESS", NULL
  1320. };
  1321. static const control_cmd_syntax_t hspost_syntax = {
  1322. .min_args = 0, .max_args = 0,
  1323. .accept_keywords = true,
  1324. .want_cmddata = true,
  1325. .allowed_keywords = hspost_keywords
  1326. };
  1327. /** Implementation for the HSPOST command. */
  1328. static int
  1329. handle_control_hspost(control_connection_t *conn,
  1330. const control_cmd_args_t *args)
  1331. {
  1332. smartlist_t *hs_dirs = NULL;
  1333. const char *encoded_desc = args->cmddata;
  1334. size_t encoded_desc_len = args->cmddata_len;
  1335. const char *onion_address = NULL;
  1336. const config_line_t *line;
  1337. for (line = args->kwargs; line; line = line->next) {
  1338. if (!strcasecmpstart(line->key, "SERVER")) {
  1339. const char *server = line->value;
  1340. const node_t *node = node_get_by_hex_id(server, 0);
  1341. if (!node || !node->rs) {
  1342. control_printf_endreply(conn, 552, "Server \"%s\" not found",
  1343. server);
  1344. goto done;
  1345. }
  1346. /* Valid server, add it to our local list. */
  1347. if (!hs_dirs)
  1348. hs_dirs = smartlist_new();
  1349. smartlist_add(hs_dirs, node->rs);
  1350. } else if (!strcasecmpstart(line->key, "HSADDRESS")) {
  1351. const char *address = line->value;
  1352. if (!hs_address_is_valid(address)) {
  1353. control_write_endreply(conn, 512, "Malformed onion address");
  1354. goto done;
  1355. }
  1356. onion_address = address;
  1357. } else {
  1358. tor_assert_nonfatal_unreached();
  1359. }
  1360. }
  1361. /* Handle the v3 case. */
  1362. if (onion_address) {
  1363. if (hs_control_hspost_command(encoded_desc, onion_address, hs_dirs) < 0) {
  1364. control_write_endreply(conn, 554, "Invalid descriptor");
  1365. } else {
  1366. send_control_done(conn);
  1367. }
  1368. goto done;
  1369. }
  1370. /* From this point on, it is only v2. */
  1371. /* parse it. */
  1372. rend_encoded_v2_service_descriptor_t *desc =
  1373. tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
  1374. desc->desc_str = tor_memdup_nulterm(encoded_desc, encoded_desc_len);
  1375. rend_service_descriptor_t *parsed = NULL;
  1376. char *intro_content = NULL;
  1377. size_t intro_size;
  1378. size_t encoded_size;
  1379. const char *next_desc;
  1380. if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
  1381. &intro_size, &encoded_size,
  1382. &next_desc, desc->desc_str, 1)) {
  1383. /* Post the descriptor. */
  1384. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1385. if (!rend_get_service_id(parsed->pk, serviceid)) {
  1386. smartlist_t *descs = smartlist_new();
  1387. smartlist_add(descs, desc);
  1388. /* We are about to trigger HS descriptor upload so send the OK now
  1389. * because after that 650 event(s) are possible so better to have the
  1390. * 250 OK before them to avoid out of order replies. */
  1391. send_control_done(conn);
  1392. /* Trigger the descriptor upload */
  1393. directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
  1394. smartlist_free(descs);
  1395. }
  1396. rend_service_descriptor_free(parsed);
  1397. } else {
  1398. control_write_endreply(conn, 554, "Invalid descriptor");
  1399. }
  1400. tor_free(intro_content);
  1401. rend_encoded_v2_service_descriptor_free(desc);
  1402. done:
  1403. smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
  1404. return 0;
  1405. }
  1406. /* Helper function for ADD_ONION that adds an ephemeral service depending on
  1407. * the given hs_version.
  1408. *
  1409. * The secret key in pk depends on the hs_version. The ownership of the key
  1410. * used in pk is given to the HS subsystem so the caller must stop accessing
  1411. * it after.
  1412. *
  1413. * The port_cfgs is a list of service port. Ownership transferred to service.
  1414. * The max_streams refers to the MaxStreams= key.
  1415. * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
  1416. * The auth_type is the authentication type of the clients in auth_clients.
  1417. * The ownership of that list is transferred to the service.
  1418. *
  1419. * On success (RSAE_OKAY), the address_out points to a newly allocated string
  1420. * containing the onion address without the .onion part. On error, address_out
  1421. * is untouched. */
  1422. static hs_service_add_ephemeral_status_t
  1423. add_onion_helper_add_service(int hs_version,
  1424. add_onion_secret_key_t *pk,
  1425. smartlist_t *port_cfgs, int max_streams,
  1426. int max_streams_close_circuit, int auth_type,
  1427. smartlist_t *auth_clients, char **address_out)
  1428. {
  1429. hs_service_add_ephemeral_status_t ret;
  1430. tor_assert(pk);
  1431. tor_assert(port_cfgs);
  1432. tor_assert(address_out);
  1433. switch (hs_version) {
  1434. case HS_VERSION_TWO:
  1435. ret = rend_service_add_ephemeral(pk->v2, port_cfgs, max_streams,
  1436. max_streams_close_circuit, auth_type,
  1437. auth_clients, address_out);
  1438. break;
  1439. case HS_VERSION_THREE:
  1440. ret = hs_service_add_ephemeral(pk->v3, port_cfgs, max_streams,
  1441. max_streams_close_circuit, address_out);
  1442. break;
  1443. default:
  1444. tor_assert_unreached();
  1445. }
  1446. return ret;
  1447. }
  1448. /** The list of onion services that have been added via ADD_ONION that do not
  1449. * belong to any particular control connection.
  1450. */
  1451. static smartlist_t *detached_onion_services = NULL;
  1452. /**
  1453. * Return a list of detached onion services, or NULL if none exist.
  1454. **/
  1455. smartlist_t *
  1456. get_detached_onion_services(void)
  1457. {
  1458. return detached_onion_services;
  1459. }
  1460. static const char *add_onion_keywords[] = {
  1461. "Port", "Flags", "MaxStreams", "ClientAuth", NULL
  1462. };
  1463. static const control_cmd_syntax_t add_onion_syntax = {
  1464. .min_args = 1, .max_args = 1,
  1465. .accept_keywords = true,
  1466. .allowed_keywords = add_onion_keywords
  1467. };
  1468. /** Called when we get a ADD_ONION command; parse the body, and set up
  1469. * the new ephemeral Onion Service. */
  1470. static int
  1471. handle_control_add_onion(control_connection_t *conn,
  1472. const control_cmd_args_t *args)
  1473. {
  1474. /* Parse all of the arguments that do not involve handling cryptographic
  1475. * material first, since there's no reason to touch that at all if any of
  1476. * the other arguments are malformed.
  1477. */
  1478. smartlist_t *port_cfgs = smartlist_new();
  1479. smartlist_t *auth_clients = NULL;
  1480. smartlist_t *auth_created_clients = NULL;
  1481. int discard_pk = 0;
  1482. int detach = 0;
  1483. int max_streams = 0;
  1484. int max_streams_close_circuit = 0;
  1485. rend_auth_type_t auth_type = REND_NO_AUTH;
  1486. int non_anonymous = 0;
  1487. const config_line_t *arg;
  1488. for (arg = args->kwargs; arg; arg = arg->next) {
  1489. if (!strcasecmp(arg->key, "Port")) {
  1490. /* "Port=VIRTPORT[,TARGET]". */
  1491. rend_service_port_config_t *cfg =
  1492. rend_service_parse_port_config(arg->value, ",", NULL);
  1493. if (!cfg) {
  1494. control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
  1495. goto out;
  1496. }
  1497. smartlist_add(port_cfgs, cfg);
  1498. } else if (!strcasecmp(arg->key, "MaxStreams")) {
  1499. /* "MaxStreams=[0..65535]". */
  1500. int ok = 0;
  1501. max_streams = (int)tor_parse_long(arg->value, 10, 0, 65535, &ok, NULL);
  1502. if (!ok) {
  1503. control_write_endreply(conn, 512, "Invalid MaxStreams");
  1504. goto out;
  1505. }
  1506. } else if (!strcasecmp(arg->key, "Flags")) {
  1507. /* "Flags=Flag[,Flag]", where Flag can be:
  1508. * * 'DiscardPK' - If tor generates the keypair, do not include it in
  1509. * the response.
  1510. * * 'Detach' - Do not tie this onion service to any particular control
  1511. * connection.
  1512. * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
  1513. * exceeded.
  1514. * * 'BasicAuth' - Client authorization using the 'basic' method.
  1515. * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
  1516. * flag is present, tor must be in non-anonymous
  1517. * hidden service mode. If this flag is absent,
  1518. * tor must be in anonymous hidden service mode.
  1519. */
  1520. static const char *discard_flag = "DiscardPK";
  1521. static const char *detach_flag = "Detach";
  1522. static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
  1523. static const char *basicauth_flag = "BasicAuth";
  1524. static const char *non_anonymous_flag = "NonAnonymous";
  1525. smartlist_t *flags = smartlist_new();
  1526. int bad = 0;
  1527. smartlist_split_string(flags, arg->value, ",", SPLIT_IGNORE_BLANK, 0);
  1528. if (smartlist_len(flags) < 1) {
  1529. control_write_endreply(conn, 512, "Invalid 'Flags' argument");
  1530. bad = 1;
  1531. }
  1532. SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
  1533. {
  1534. if (!strcasecmp(flag, discard_flag)) {
  1535. discard_pk = 1;
  1536. } else if (!strcasecmp(flag, detach_flag)) {
  1537. detach = 1;
  1538. } else if (!strcasecmp(flag, max_s_close_flag)) {
  1539. max_streams_close_circuit = 1;
  1540. } else if (!strcasecmp(flag, basicauth_flag)) {
  1541. auth_type = REND_BASIC_AUTH;
  1542. } else if (!strcasecmp(flag, non_anonymous_flag)) {
  1543. non_anonymous = 1;
  1544. } else {
  1545. control_printf_endreply(conn, 512, "Invalid 'Flags' argument: %s",
  1546. escaped(flag));
  1547. bad = 1;
  1548. break;
  1549. }
  1550. } SMARTLIST_FOREACH_END(flag);
  1551. SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
  1552. smartlist_free(flags);
  1553. if (bad)
  1554. goto out;
  1555. } else if (!strcasecmp(arg->key, "ClientAuth")) {
  1556. int created = 0;
  1557. rend_authorized_client_t *client =
  1558. add_onion_helper_clientauth(arg->value, &created, conn);
  1559. if (!client) {
  1560. goto out;
  1561. }
  1562. if (auth_clients != NULL) {
  1563. int bad = 0;
  1564. SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
  1565. if (strcmp(ac->client_name, client->client_name) == 0) {
  1566. bad = 1;
  1567. break;
  1568. }
  1569. } SMARTLIST_FOREACH_END(ac);
  1570. if (bad) {
  1571. control_write_endreply(conn, 512, "Duplicate name in ClientAuth");
  1572. rend_authorized_client_free(client);
  1573. goto out;
  1574. }
  1575. } else {
  1576. auth_clients = smartlist_new();
  1577. auth_created_clients = smartlist_new();
  1578. }
  1579. smartlist_add(auth_clients, client);
  1580. if (created) {
  1581. smartlist_add(auth_created_clients, client);
  1582. }
  1583. } else {
  1584. tor_assert_nonfatal_unreached();
  1585. goto out;
  1586. }
  1587. }
  1588. if (smartlist_len(port_cfgs) == 0) {
  1589. control_write_endreply(conn, 512, "Missing 'Port' argument");
  1590. goto out;
  1591. } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
  1592. control_write_endreply(conn, 512, "No auth type specified");
  1593. goto out;
  1594. } else if (auth_type != REND_NO_AUTH && auth_clients == NULL) {
  1595. control_write_endreply(conn, 512, "No auth clients specified");
  1596. goto out;
  1597. } else if ((auth_type == REND_BASIC_AUTH &&
  1598. smartlist_len(auth_clients) > 512) ||
  1599. (auth_type == REND_STEALTH_AUTH &&
  1600. smartlist_len(auth_clients) > 16)) {
  1601. control_write_endreply(conn, 512, "Too many auth clients");
  1602. goto out;
  1603. } else if (non_anonymous != rend_service_non_anonymous_mode_enabled(
  1604. get_options())) {
  1605. /* If we failed, and the non-anonymous flag is set, Tor must be in
  1606. * anonymous hidden service mode.
  1607. * The error message changes based on the current Tor config:
  1608. * 512 Tor is in anonymous hidden service mode
  1609. * 512 Tor is in non-anonymous hidden service mode
  1610. * (I've deliberately written them out in full here to aid searchability.)
  1611. */
  1612. control_printf_endreply(conn, 512,
  1613. "Tor is in %sanonymous hidden service " "mode",
  1614. non_anonymous ? "" : "non-");
  1615. goto out;
  1616. }
  1617. /* Parse the "keytype:keyblob" argument. */
  1618. int hs_version = 0;
  1619. add_onion_secret_key_t pk = { NULL };
  1620. const char *key_new_alg = NULL;
  1621. char *key_new_blob = NULL;
  1622. const char *onionkey = smartlist_get(args->args, 0);
  1623. if (add_onion_helper_keyarg(onionkey, discard_pk,
  1624. &key_new_alg, &key_new_blob, &pk, &hs_version,
  1625. conn) < 0) {
  1626. goto out;
  1627. }
  1628. /* Hidden service version 3 don't have client authentication support so if
  1629. * ClientAuth was given, send back an error. */
  1630. if (hs_version == HS_VERSION_THREE && auth_clients) {
  1631. control_write_endreply(conn, 513, "ClientAuth not supported");
  1632. goto out;
  1633. }
  1634. /* Create the HS, using private key pk, client authentication auth_type,
  1635. * the list of auth_clients, and port config port_cfg.
  1636. * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
  1637. * regardless of success/failure.
  1638. */
  1639. char *service_id = NULL;
  1640. int ret = add_onion_helper_add_service(hs_version, &pk, port_cfgs,
  1641. max_streams,
  1642. max_streams_close_circuit, auth_type,
  1643. auth_clients, &service_id);
  1644. port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
  1645. auth_clients = NULL; /* so is auth_clients */
  1646. switch (ret) {
  1647. case RSAE_OKAY:
  1648. {
  1649. if (detach) {
  1650. if (!detached_onion_services)
  1651. detached_onion_services = smartlist_new();
  1652. smartlist_add(detached_onion_services, service_id);
  1653. } else {
  1654. if (!conn->ephemeral_onion_services)
  1655. conn->ephemeral_onion_services = smartlist_new();
  1656. smartlist_add(conn->ephemeral_onion_services, service_id);
  1657. }
  1658. tor_assert(service_id);
  1659. control_printf_midreply(conn, 250, "ServiceID=%s", service_id);
  1660. if (key_new_alg) {
  1661. tor_assert(key_new_blob);
  1662. control_printf_midreply(conn, 250, "PrivateKey=%s:%s",
  1663. key_new_alg, key_new_blob);
  1664. }
  1665. if (auth_created_clients) {
  1666. SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
  1667. char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
  1668. auth_type);
  1669. tor_assert(encoded);
  1670. control_printf_midreply(conn, 250, "ClientAuth=%s:%s",
  1671. ac->client_name, encoded);
  1672. memwipe(encoded, 0, strlen(encoded));
  1673. tor_free(encoded);
  1674. });
  1675. }
  1676. send_control_done(conn);
  1677. break;
  1678. }
  1679. case RSAE_BADPRIVKEY:
  1680. control_write_endreply(conn, 551, "Failed to generate onion address");
  1681. break;
  1682. case RSAE_ADDREXISTS:
  1683. control_write_endreply(conn, 550, "Onion address collision");
  1684. break;
  1685. case RSAE_BADVIRTPORT:
  1686. control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
  1687. break;
  1688. case RSAE_BADAUTH:
  1689. control_write_endreply(conn, 512, "Invalid client authorization");
  1690. break;
  1691. case RSAE_INTERNAL: /* FALLSTHROUGH */
  1692. default:
  1693. control_write_endreply(conn, 551, "Failed to add Onion Service");
  1694. }
  1695. if (key_new_blob) {
  1696. memwipe(key_new_blob, 0, strlen(key_new_blob));
  1697. tor_free(key_new_blob);
  1698. }
  1699. out:
  1700. if (port_cfgs) {
  1701. SMARTLIST_FOREACH(port_cfgs, rend_service_port_config_t*, p,
  1702. rend_service_port_config_free(p));
  1703. smartlist_free(port_cfgs);
  1704. }
  1705. if (auth_clients) {
  1706. SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
  1707. rend_authorized_client_free(ac));
  1708. smartlist_free(auth_clients);
  1709. }
  1710. if (auth_created_clients) {
  1711. // Do not free entries; they are the same as auth_clients
  1712. smartlist_free(auth_created_clients);
  1713. }
  1714. return 0;
  1715. }
  1716. /** Helper function to handle parsing the KeyType:KeyBlob argument to the
  1717. * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
  1718. * and the private key not discarded, the algorithm and serialized private key,
  1719. * or NULL and an optional control protocol error message on failure. The
  1720. * caller is responsible for freeing the returned key_new_blob.
  1721. *
  1722. * Note: The error messages returned are deliberately vague to avoid echoing
  1723. * key material.
  1724. *
  1725. * Note: conn is only used for writing control replies. For testing
  1726. * purposes, it can be NULL if control_write_reply() is appropriately
  1727. * mocked.
  1728. */
  1729. STATIC int
  1730. add_onion_helper_keyarg(const char *arg, int discard_pk,
  1731. const char **key_new_alg_out, char **key_new_blob_out,
  1732. add_onion_secret_key_t *decoded_key, int *hs_version,
  1733. control_connection_t *conn)
  1734. {
  1735. smartlist_t *key_args = smartlist_new();
  1736. crypto_pk_t *pk = NULL;
  1737. const char *key_new_alg = NULL;
  1738. char *key_new_blob = NULL;
  1739. int ret = -1;
  1740. smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
  1741. if (smartlist_len(key_args) != 2) {
  1742. control_write_endreply(conn, 512, "Invalid key type/blob");
  1743. goto err;
  1744. }
  1745. /* The format is "KeyType:KeyBlob". */
  1746. static const char *key_type_new = "NEW";
  1747. static const char *key_type_best = "BEST";
  1748. static const char *key_type_rsa1024 = "RSA1024";
  1749. static const char *key_type_ed25519_v3 = "ED25519-V3";
  1750. const char *key_type = smartlist_get(key_args, 0);
  1751. const char *key_blob = smartlist_get(key_args, 1);
  1752. if (!strcasecmp(key_type_rsa1024, key_type)) {
  1753. /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
  1754. pk = crypto_pk_base64_decode_private(key_blob, strlen(key_blob));
  1755. if (!pk) {
  1756. control_write_endreply(conn, 512, "Failed to decode RSA key");
  1757. goto err;
  1758. }
  1759. if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
  1760. crypto_pk_free(pk);
  1761. control_write_endreply(conn, 512, "Invalid RSA key size");
  1762. goto err;
  1763. }
  1764. decoded_key->v2 = pk;
  1765. *hs_version = HS_VERSION_TWO;
  1766. } else if (!strcasecmp(key_type_ed25519_v3, key_type)) {
  1767. /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
  1768. ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
  1769. if (base64_decode((char *) sk->seckey, sizeof(sk->seckey), key_blob,
  1770. strlen(key_blob)) != sizeof(sk->seckey)) {
  1771. tor_free(sk);
  1772. control_write_endreply(conn, 512, "Failed to decode ED25519-V3 key");
  1773. goto err;
  1774. }
  1775. decoded_key->v3 = sk;
  1776. *hs_version = HS_VERSION_THREE;
  1777. } else if (!strcasecmp(key_type_new, key_type)) {
  1778. /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
  1779. if (!strcasecmp(key_type_rsa1024, key_blob) ||
  1780. !strcasecmp(key_type_best, key_blob)) {
  1781. /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
  1782. pk = crypto_pk_new();
  1783. if (crypto_pk_generate_key(pk)) {
  1784. control_printf_endreply(conn, 551, "Failed to generate %s key",
  1785. key_type_rsa1024);
  1786. goto err;
  1787. }
  1788. if (!discard_pk) {
  1789. if (crypto_pk_base64_encode_private(pk, &key_new_blob)) {
  1790. crypto_pk_free(pk);
  1791. control_printf_endreply(conn, 551, "Failed to encode %s key",
  1792. key_type_rsa1024);
  1793. goto err;
  1794. }
  1795. key_new_alg = key_type_rsa1024;
  1796. }
  1797. decoded_key->v2 = pk;
  1798. *hs_version = HS_VERSION_TWO;
  1799. } else if (!strcasecmp(key_type_ed25519_v3, key_blob)) {
  1800. ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
  1801. if (ed25519_secret_key_generate(sk, 1) < 0) {
  1802. tor_free(sk);
  1803. control_printf_endreply(conn, 551, "Failed to generate %s key",
  1804. key_type_ed25519_v3);
  1805. goto err;
  1806. }
  1807. if (!discard_pk) {
  1808. ssize_t len = base64_encode_size(sizeof(sk->seckey), 0) + 1;
  1809. key_new_blob = tor_malloc_zero(len);
  1810. if (base64_encode(key_new_blob, len, (const char *) sk->seckey,
  1811. sizeof(sk->seckey), 0) != (len - 1)) {
  1812. tor_free(sk);
  1813. tor_free(key_new_blob);
  1814. control_printf_endreply(conn, 551, "Failed to encode %s key",
  1815. key_type_ed25519_v3);
  1816. goto err;
  1817. }
  1818. key_new_alg = key_type_ed25519_v3;
  1819. }
  1820. decoded_key->v3 = sk;
  1821. *hs_version = HS_VERSION_THREE;
  1822. } else {
  1823. control_write_endreply(conn, 513, "Invalid key type");
  1824. goto err;
  1825. }
  1826. } else {
  1827. control_write_endreply(conn, 513, "Invalid key type");
  1828. goto err;
  1829. }
  1830. /* Succeeded in loading or generating a private key. */
  1831. ret = 0;
  1832. err:
  1833. SMARTLIST_FOREACH(key_args, char *, cp, {
  1834. memwipe(cp, 0, strlen(cp));
  1835. tor_free(cp);
  1836. });
  1837. smartlist_free(key_args);
  1838. *key_new_alg_out = key_new_alg;
  1839. *key_new_blob_out = key_new_blob;
  1840. return ret;
  1841. }
  1842. /** Helper function to handle parsing a ClientAuth argument to the
  1843. * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
  1844. * and an optional control protocol error message on failure. The
  1845. * caller is responsible for freeing the returned auth_client.
  1846. *
  1847. * If 'created' is specified, it will be set to 1 when a new cookie has
  1848. * been generated.
  1849. *
  1850. * Note: conn is only used for writing control replies. For testing
  1851. * purposes, it can be NULL if control_write_reply() is appropriately
  1852. * mocked.
  1853. */
  1854. STATIC rend_authorized_client_t *
  1855. add_onion_helper_clientauth(const char *arg, int *created,
  1856. control_connection_t *conn)
  1857. {
  1858. int ok = 0;
  1859. tor_assert(arg);
  1860. tor_assert(created);
  1861. smartlist_t *auth_args = smartlist_new();
  1862. rend_authorized_client_t *client =
  1863. tor_malloc_zero(sizeof(rend_authorized_client_t));
  1864. smartlist_split_string(auth_args, arg, ":", 0, 0);
  1865. if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
  1866. control_write_endreply(conn, 512, "Invalid ClientAuth syntax");
  1867. goto err;
  1868. }
  1869. client->client_name = tor_strdup(smartlist_get(auth_args, 0));
  1870. if (smartlist_len(auth_args) == 2) {
  1871. char *decode_err_msg = NULL;
  1872. if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
  1873. client->descriptor_cookie,
  1874. NULL, &decode_err_msg) < 0) {
  1875. tor_assert(decode_err_msg);
  1876. control_write_endreply(conn, 512, decode_err_msg);
  1877. tor_free(decode_err_msg);
  1878. goto err;
  1879. }
  1880. *created = 0;
  1881. } else {
  1882. crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  1883. *created = 1;
  1884. }
  1885. if (!rend_valid_client_name(client->client_name)) {
  1886. control_write_endreply(conn, 512, "Invalid name in ClientAuth");
  1887. goto err;
  1888. }
  1889. ok = 1;
  1890. err:
  1891. SMARTLIST_FOREACH(auth_args, char *, item, tor_free(item));
  1892. smartlist_free(auth_args);
  1893. if (!ok) {
  1894. rend_authorized_client_free(client);
  1895. client = NULL;
  1896. }
  1897. return client;
  1898. }
  1899. static const control_cmd_syntax_t del_onion_syntax = {
  1900. .min_args = 1, .max_args = 1,
  1901. };
  1902. /** Called when we get a DEL_ONION command; parse the body, and remove
  1903. * the existing ephemeral Onion Service. */
  1904. static int
  1905. handle_control_del_onion(control_connection_t *conn,
  1906. const control_cmd_args_t *cmd_args)
  1907. {
  1908. int hs_version = 0;
  1909. smartlist_t *args = cmd_args->args;
  1910. tor_assert(smartlist_len(args) == 1);
  1911. const char *service_id = smartlist_get(args, 0);
  1912. if (rend_valid_v2_service_id(service_id)) {
  1913. hs_version = HS_VERSION_TWO;
  1914. } else if (hs_address_is_valid(service_id)) {
  1915. hs_version = HS_VERSION_THREE;
  1916. } else {
  1917. control_write_endreply(conn, 512, "Malformed Onion Service id");
  1918. goto out;
  1919. }
  1920. /* Determine if the onion service belongs to this particular control
  1921. * connection, or if it is in the global list of detached services. If it
  1922. * is in neither, either the service ID is invalid in some way, or it
  1923. * explicitly belongs to a different control connection, and an error
  1924. * should be returned.
  1925. */
  1926. smartlist_t *services[2] = {
  1927. conn->ephemeral_onion_services,
  1928. detached_onion_services
  1929. };
  1930. smartlist_t *onion_services = NULL;
  1931. int idx = -1;
  1932. for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
  1933. idx = smartlist_string_pos(services[i], service_id);
  1934. if (idx != -1) {
  1935. onion_services = services[i];
  1936. break;
  1937. }
  1938. }
  1939. if (onion_services == NULL) {
  1940. control_write_endreply(conn, 552, "Unknown Onion Service id");
  1941. } else {
  1942. int ret = -1;
  1943. switch (hs_version) {
  1944. case HS_VERSION_TWO:
  1945. ret = rend_service_del_ephemeral(service_id);
  1946. break;
  1947. case HS_VERSION_THREE:
  1948. ret = hs_service_del_ephemeral(service_id);
  1949. break;
  1950. default:
  1951. /* The ret value will be -1 thus hitting the warning below. This should
  1952. * never happen because of the check at the start of the function. */
  1953. break;
  1954. }
  1955. if (ret < 0) {
  1956. /* This should *NEVER* fail, since the service is on either the
  1957. * per-control connection list, or the global one.
  1958. */
  1959. log_warn(LD_BUG, "Failed to remove Onion Service %s.",
  1960. escaped(service_id));
  1961. tor_fragile_assert();
  1962. }
  1963. /* Remove/scrub the service_id from the appropriate list. */
  1964. char *cp = smartlist_get(onion_services, idx);
  1965. smartlist_del(onion_services, idx);
  1966. memwipe(cp, 0, strlen(cp));
  1967. tor_free(cp);
  1968. send_control_done(conn);
  1969. }
  1970. out:
  1971. return 0;
  1972. }
  1973. static const control_cmd_syntax_t obsolete_syntax = {
  1974. .max_args = UINT_MAX
  1975. };
  1976. /**
  1977. * Called when we get an obsolete command: tell the controller that it is
  1978. * obsolete.
  1979. */
  1980. static int
  1981. handle_control_obsolete(control_connection_t *conn,
  1982. const control_cmd_args_t *args)
  1983. {
  1984. (void)args;
  1985. char *command = tor_strdup(conn->current_cmd);
  1986. tor_strupper(command);
  1987. control_printf_endreply(conn, 511, "%s is obsolete.", command);
  1988. tor_free(command);
  1989. return 0;
  1990. }
  1991. /**
  1992. * Function pointer to a handler function for a controller command.
  1993. **/
  1994. typedef int (*handler_fn_t) (control_connection_t *conn,
  1995. const control_cmd_args_t *args);
  1996. /**
  1997. * Definition for a controller command.
  1998. */
  1999. typedef struct control_cmd_def_t {
  2000. /**
  2001. * The name of the command. If the command is multiline, the name must
  2002. * begin with "+". This is not case-sensitive. */
  2003. const char *name;
  2004. /**
  2005. * A function to execute the command.
  2006. */
  2007. handler_fn_t handler;
  2008. /**
  2009. * Zero or more CMD_FL_* flags, or'd together.
  2010. */
  2011. unsigned flags;
  2012. /**
  2013. * For parsed command: a syntax description.
  2014. */
  2015. const control_cmd_syntax_t *syntax;
  2016. } control_cmd_def_t;
  2017. /**
  2018. * Indicates that the command's arguments are sensitive, and should be
  2019. * memwiped after use.
  2020. */
  2021. #define CMD_FL_WIPE (1u<<0)
  2022. /** Macro: declare a command with a one-line argument, a given set of flags,
  2023. * and a syntax definition.
  2024. **/
  2025. #define ONE_LINE(name, flags) \
  2026. { \
  2027. #name, \
  2028. handle_control_ ##name, \
  2029. flags, \
  2030. &name##_syntax, \
  2031. }
  2032. /**
  2033. * Macro: declare a command with a multi-line argument and a given set of
  2034. * flags.
  2035. **/
  2036. #define MULTLINE(name, flags) \
  2037. { "+"#name, \
  2038. handle_control_ ##name, \
  2039. flags, \
  2040. &name##_syntax \
  2041. }
  2042. /**
  2043. * Macro: declare an obsolete command. (Obsolete commands give a different
  2044. * error than non-existent ones.)
  2045. **/
  2046. #define OBSOLETE(name) \
  2047. { #name, \
  2048. handle_control_obsolete, \
  2049. 0, \
  2050. &obsolete_syntax, \
  2051. }
  2052. /**
  2053. * An array defining all the recognized controller commands.
  2054. **/
  2055. static const control_cmd_def_t CONTROL_COMMANDS[] =
  2056. {
  2057. ONE_LINE(setconf, 0),
  2058. ONE_LINE(resetconf, 0),
  2059. ONE_LINE(getconf, 0),
  2060. MULTLINE(loadconf, 0),
  2061. ONE_LINE(setevents, 0),
  2062. ONE_LINE(authenticate, CMD_FL_WIPE),
  2063. ONE_LINE(saveconf, 0),
  2064. ONE_LINE(signal, 0),
  2065. ONE_LINE(takeownership, 0),
  2066. ONE_LINE(dropownership, 0),
  2067. ONE_LINE(mapaddress, 0),
  2068. ONE_LINE(getinfo, 0),
  2069. ONE_LINE(extendcircuit, 0),
  2070. ONE_LINE(setcircuitpurpose, 0),
  2071. OBSOLETE(setrouterpurpose),
  2072. ONE_LINE(attachstream, 0),
  2073. MULTLINE(postdescriptor, 0),
  2074. ONE_LINE(redirectstream, 0),
  2075. ONE_LINE(closestream, 0),
  2076. ONE_LINE(closecircuit, 0),
  2077. ONE_LINE(usefeature, 0),
  2078. ONE_LINE(resolve, 0),
  2079. ONE_LINE(protocolinfo, 0),
  2080. ONE_LINE(authchallenge, CMD_FL_WIPE),
  2081. ONE_LINE(dropguards, 0),
  2082. ONE_LINE(hsfetch, 0),
  2083. MULTLINE(hspost, 0),
  2084. ONE_LINE(add_onion, CMD_FL_WIPE),
  2085. ONE_LINE(del_onion, CMD_FL_WIPE),
  2086. };
  2087. /**
  2088. * The number of entries in CONTROL_COMMANDS.
  2089. **/
  2090. static const size_t N_CONTROL_COMMANDS = ARRAY_LENGTH(CONTROL_COMMANDS);
  2091. /**
  2092. * Run a single control command, as defined by a control_cmd_def_t,
  2093. * with a given set of arguments.
  2094. */
  2095. static int
  2096. handle_single_control_command(const control_cmd_def_t *def,
  2097. control_connection_t *conn,
  2098. uint32_t cmd_data_len,
  2099. char *args)
  2100. {
  2101. int rv = 0;
  2102. control_cmd_args_t *parsed_args;
  2103. char *err=NULL;
  2104. tor_assert(def->syntax);
  2105. parsed_args = control_cmd_parse_args(conn->current_cmd,
  2106. def->syntax,
  2107. cmd_data_len, args,
  2108. &err);
  2109. if (!parsed_args) {
  2110. control_printf_endreply(conn, 512, "Bad arguments to %s: %s",
  2111. conn->current_cmd, err?err:"");
  2112. tor_free(err);
  2113. } else {
  2114. if (BUG(err))
  2115. tor_free(err);
  2116. if (def->handler(conn, parsed_args))
  2117. rv = 0;
  2118. if (def->flags & CMD_FL_WIPE)
  2119. control_cmd_args_wipe(parsed_args);
  2120. control_cmd_args_free(parsed_args);
  2121. }
  2122. if (def->flags & CMD_FL_WIPE)
  2123. memwipe(args, 0, cmd_data_len);
  2124. return rv;
  2125. }
  2126. /**
  2127. * Run a given controller command, as selected by the current_cmd field of
  2128. * <b>conn</b>.
  2129. */
  2130. int
  2131. handle_control_command(control_connection_t *conn,
  2132. uint32_t cmd_data_len,
  2133. char *args)
  2134. {
  2135. tor_assert(conn);
  2136. tor_assert(args);
  2137. tor_assert(args[cmd_data_len] == '\0');
  2138. for (unsigned i = 0; i < N_CONTROL_COMMANDS; ++i) {
  2139. const control_cmd_def_t *def = &CONTROL_COMMANDS[i];
  2140. if (!strcasecmp(conn->current_cmd, def->name)) {
  2141. return handle_single_control_command(def, conn, cmd_data_len, args);
  2142. }
  2143. }
  2144. control_printf_endreply(conn, 510, "Unrecognized command \"%s\"",
  2145. conn->current_cmd);
  2146. return 0;
  2147. }
  2148. void
  2149. control_cmd_free_all(void)
  2150. {
  2151. if (detached_onion_services) { /* Free the detached onion services */
  2152. SMARTLIST_FOREACH(detached_onion_services, char *, cp, tor_free(cp));
  2153. smartlist_free(detached_onion_services);
  2154. }
  2155. }