control_cmd.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399
  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. // no positional arguments are expected
  566. .max_args=0,
  567. // an arbitrary number of K=V entries are supported.
  568. .accept_keywords=true,
  569. };
  570. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  571. * and report success or failure. */
  572. static int
  573. handle_control_mapaddress(control_connection_t *conn,
  574. const control_cmd_args_t *args)
  575. {
  576. smartlist_t *reply;
  577. char *r;
  578. size_t sz;
  579. reply = smartlist_new();
  580. const config_line_t *line;
  581. for (line = args->kwargs; line; line = line->next) {
  582. const char *from = line->key;
  583. const char *to = line->value;
  584. {
  585. if (address_is_invalid_mapaddress_target(to)) {
  586. smartlist_add_asprintf(reply,
  587. "512-syntax error: invalid address '%s'", to);
  588. log_warn(LD_CONTROL,
  589. "Skipping invalid argument '%s' in MapAddress msg", to);
  590. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
  591. !strcmp(from, "::")) {
  592. const char type =
  593. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
  594. (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
  595. const char *address = addressmap_register_virtual_address(
  596. type, tor_strdup(to));
  597. if (!address) {
  598. smartlist_add_asprintf(reply,
  599. "451-resource exhausted: skipping '%s=%s'", from,to);
  600. log_warn(LD_CONTROL,
  601. "Unable to allocate address for '%s' in MapAddress msg",
  602. safe_str_client(to));
  603. } else {
  604. smartlist_add_asprintf(reply, "250-%s=%s", address, to);
  605. }
  606. } else {
  607. const char *msg;
  608. if (addressmap_register_auto(from, to, 1,
  609. ADDRMAPSRC_CONTROLLER, &msg) < 0) {
  610. smartlist_add_asprintf(reply,
  611. "512-syntax error: invalid address mapping "
  612. " '%s=%s': %s", from, to, msg);
  613. log_warn(LD_CONTROL,
  614. "Skipping invalid argument '%s=%s' in MapAddress msg: %s",
  615. from, to, msg);
  616. } else {
  617. smartlist_add_asprintf(reply, "250-%s=%s", from, to);
  618. }
  619. }
  620. }
  621. }
  622. if (smartlist_len(reply)) {
  623. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  624. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  625. connection_buf_add(r, sz, TO_CONN(conn));
  626. tor_free(r);
  627. } else {
  628. control_write_endreply(conn, 512, "syntax error: "
  629. "not enough arguments to mapaddress.");
  630. }
  631. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  632. smartlist_free(reply);
  633. return 0;
  634. }
  635. /** Given a string, convert it to a circuit purpose. */
  636. static uint8_t
  637. circuit_purpose_from_string(const char *string)
  638. {
  639. if (!strcasecmpstart(string, "purpose="))
  640. string += strlen("purpose=");
  641. if (!strcasecmp(string, "general"))
  642. return CIRCUIT_PURPOSE_C_GENERAL;
  643. else if (!strcasecmp(string, "controller"))
  644. return CIRCUIT_PURPOSE_CONTROLLER;
  645. else
  646. return CIRCUIT_PURPOSE_UNKNOWN;
  647. }
  648. static const control_cmd_syntax_t extendcircuit_syntax = {
  649. .min_args=1,
  650. .max_args=1, // see note in function
  651. .accept_keywords=true,
  652. .kvline_flags=KV_OMIT_VALS
  653. };
  654. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  655. * circuit, and report success or failure. */
  656. static int
  657. handle_control_extendcircuit(control_connection_t *conn,
  658. const control_cmd_args_t *args)
  659. {
  660. smartlist_t *router_nicknames=smartlist_new(), *nodes=NULL;
  661. origin_circuit_t *circ = NULL;
  662. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  663. const config_line_t *kwargs = args->kwargs;
  664. const char *circ_id = smartlist_get(args->args, 0);
  665. const char *path_str = NULL;
  666. char *path_str_alloc = NULL;
  667. /* The syntax for this command is unfortunate. The second argument is
  668. optional, and is a comma-separated list long-format fingerprints, which
  669. can (historically!) contain an equals sign.
  670. Here we check the second argument to see if it's a path, and if so we
  671. remove it from the kwargs list and put it in path_str.
  672. */
  673. if (kwargs) {
  674. const config_line_t *arg1 = kwargs;
  675. if (!strcmp(arg1->value, "")) {
  676. path_str = arg1->key;
  677. kwargs = kwargs->next;
  678. } else if (arg1->key[0] == '$') {
  679. tor_asprintf(&path_str_alloc, "%s=%s", arg1->key, arg1->value);
  680. path_str = path_str_alloc;
  681. kwargs = kwargs->next;
  682. }
  683. }
  684. const config_line_t *purpose_line = config_line_find_case(kwargs, "PURPOSE");
  685. bool zero_circ = !strcmp("0", circ_id);
  686. if (purpose_line) {
  687. intended_purpose = circuit_purpose_from_string(purpose_line->value);
  688. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  689. control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
  690. purpose_line->value);
  691. goto done;
  692. }
  693. }
  694. if (zero_circ) {
  695. if (!path_str) {
  696. // "EXTENDCIRCUIT 0" with no path.
  697. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  698. if (!circ) {
  699. control_write_endreply(conn, 551, "Couldn't start circuit");
  700. } else {
  701. control_printf_endreply(conn, 250, "EXTENDED %lu",
  702. (unsigned long)circ->global_identifier);
  703. }
  704. goto done;
  705. }
  706. }
  707. if (!zero_circ && !(circ = get_circ(circ_id))) {
  708. control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
  709. goto done;
  710. }
  711. if (!path_str) {
  712. control_write_endreply(conn, 512, "syntax error: path required.");
  713. goto done;
  714. }
  715. smartlist_split_string(router_nicknames, path_str, ",", 0, 0);
  716. nodes = smartlist_new();
  717. bool first_node = zero_circ;
  718. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  719. const node_t *node = node_get_by_nickname(n, 0);
  720. if (!node) {
  721. control_printf_endreply(conn, 552, "No such router \"%s\"", n);
  722. goto done;
  723. }
  724. if (!node_has_preferred_descriptor(node, first_node)) {
  725. control_printf_endreply(conn, 552, "No descriptor for \"%s\"", n);
  726. goto done;
  727. }
  728. smartlist_add(nodes, (void*)node);
  729. first_node = false;
  730. } SMARTLIST_FOREACH_END(n);
  731. if (!smartlist_len(nodes)) {
  732. control_write_endreply(conn, 512, "No router names provided");
  733. goto done;
  734. }
  735. if (zero_circ) {
  736. /* start a new circuit */
  737. circ = origin_circuit_init(intended_purpose, 0);
  738. }
  739. /* now circ refers to something that is ready to be extended */
  740. first_node = zero_circ;
  741. SMARTLIST_FOREACH(nodes, const node_t *, node,
  742. {
  743. extend_info_t *info = extend_info_from_node(node, first_node);
  744. if (!info) {
  745. tor_assert_nonfatal(first_node);
  746. log_warn(LD_CONTROL,
  747. "controller tried to connect to a node that lacks a suitable "
  748. "descriptor, or which doesn't have any "
  749. "addresses that are allowed by the firewall configuration; "
  750. "circuit marked for closing.");
  751. circuit_mark_for_close(TO_CIRCUIT(circ), -END_CIRC_REASON_CONNECTFAILED);
  752. control_write_endreply(conn, 551, "Couldn't start circuit");
  753. goto done;
  754. }
  755. circuit_append_new_exit(circ, info);
  756. if (circ->build_state->desired_path_len > 1) {
  757. circ->build_state->onehop_tunnel = 0;
  758. }
  759. extend_info_free(info);
  760. first_node = 0;
  761. });
  762. /* now that we've populated the cpath, start extending */
  763. if (zero_circ) {
  764. int err_reason = 0;
  765. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  766. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  767. control_write_endreply(conn, 551, "Couldn't start circuit");
  768. goto done;
  769. }
  770. } else {
  771. if (circ->base_.state == CIRCUIT_STATE_OPEN ||
  772. circ->base_.state == CIRCUIT_STATE_GUARD_WAIT) {
  773. int err_reason = 0;
  774. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  775. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  776. log_info(LD_CONTROL,
  777. "send_next_onion_skin failed; circuit marked for closing.");
  778. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  779. control_write_endreply(conn, 551, "Couldn't send onion skin");
  780. goto done;
  781. }
  782. }
  783. }
  784. control_printf_endreply(conn, 250, "EXTENDED %lu",
  785. (unsigned long)circ->global_identifier);
  786. if (zero_circ) /* send a 'launched' event, for completeness */
  787. circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
  788. done:
  789. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  790. smartlist_free(router_nicknames);
  791. smartlist_free(nodes);
  792. tor_free(path_str_alloc);
  793. return 0;
  794. }
  795. static const control_cmd_syntax_t setcircuitpurpose_syntax = {
  796. .max_args=1,
  797. .accept_keywords=true,
  798. };
  799. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  800. * circuit and it's a valid purpose, change it. */
  801. static int
  802. handle_control_setcircuitpurpose(control_connection_t *conn,
  803. const control_cmd_args_t *args)
  804. {
  805. origin_circuit_t *circ = NULL;
  806. uint8_t new_purpose;
  807. const char *circ_id = smartlist_get(args->args,0);
  808. if (!(circ = get_circ(circ_id))) {
  809. control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
  810. goto done;
  811. }
  812. {
  813. const config_line_t *purp = config_line_find_case(args->kwargs, "PURPOSE");
  814. if (!purp) {
  815. control_write_endreply(conn, 552, "No purpose given");
  816. goto done;
  817. }
  818. new_purpose = circuit_purpose_from_string(purp->value);
  819. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  820. control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
  821. purp->value);
  822. goto done;
  823. }
  824. }
  825. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  826. send_control_done(conn);
  827. done:
  828. return 0;
  829. }
  830. static const char *attachstream_keywords[] = {
  831. "HOP", NULL
  832. };
  833. static const control_cmd_syntax_t attachstream_syntax = {
  834. .min_args=2, .max_args=2,
  835. .accept_keywords=true,
  836. .allowed_keywords=attachstream_keywords
  837. };
  838. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  839. * stream, and report success or failure. */
  840. static int
  841. handle_control_attachstream(control_connection_t *conn,
  842. const control_cmd_args_t *args)
  843. {
  844. entry_connection_t *ap_conn = NULL;
  845. origin_circuit_t *circ = NULL;
  846. crypt_path_t *cpath=NULL;
  847. int hop=0, hop_line_ok=1;
  848. const char *stream_id = smartlist_get(args->args, 0);
  849. const char *circ_id = smartlist_get(args->args, 1);
  850. int zero_circ = !strcmp(circ_id, "0");
  851. const config_line_t *hoparg = config_line_find_case(args->kwargs, "HOP");
  852. if (!(ap_conn = get_stream(stream_id))) {
  853. control_printf_endreply(conn, 552, "Unknown stream \"%s\"", stream_id);
  854. return 0;
  855. } else if (!zero_circ && !(circ = get_circ(circ_id))) {
  856. control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
  857. return 0;
  858. } else if (circ) {
  859. if (hoparg) {
  860. hop = (int) tor_parse_ulong(hoparg->value, 10, 0, INT_MAX,
  861. &hop_line_ok, NULL);
  862. if (!hop_line_ok) { /* broken hop line */
  863. control_printf_endreply(conn, 552, "Bad value hop=%s",
  864. hoparg->value);
  865. return 0;
  866. }
  867. }
  868. }
  869. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  870. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  871. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  872. control_write_endreply(conn, 555,
  873. "Connection is not managed by controller.");
  874. return 0;
  875. }
  876. /* Do we need to detach it first? */
  877. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  878. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  879. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  880. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  881. /* Un-mark it as ending, since we're going to reuse it. */
  882. edge_conn->edge_has_sent_end = 0;
  883. edge_conn->end_reason = 0;
  884. if (tmpcirc)
  885. circuit_detach_stream(tmpcirc, edge_conn);
  886. CONNECTION_AP_EXPECT_NONPENDING(ap_conn);
  887. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  888. }
  889. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  890. control_write_endreply(conn, 551,
  891. "Can't attach stream to non-open origin circuit");
  892. return 0;
  893. }
  894. /* Is this a single hop circuit? */
  895. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  896. control_write_endreply(conn, 551,
  897. "Can't attach stream to this one-hop circuit.");
  898. return 0;
  899. }
  900. if (circ && hop>0) {
  901. /* find this hop in the circuit, and set cpath */
  902. cpath = circuit_get_cpath_hop(circ, hop);
  903. if (!cpath) {
  904. control_printf_endreply(conn, 551, "Circuit doesn't have %d hops.", hop);
  905. return 0;
  906. }
  907. }
  908. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  909. control_write_endreply(conn, 551, "Unable to attach stream");
  910. return 0;
  911. }
  912. send_control_done(conn);
  913. return 0;
  914. }
  915. static const char *postdescriptor_keywords[] = {
  916. "cache", "purpose", NULL,
  917. };
  918. static const control_cmd_syntax_t postdescriptor_syntax = {
  919. .max_args = 0,
  920. .accept_keywords = true,
  921. .allowed_keywords = postdescriptor_keywords,
  922. .want_cmddata = true,
  923. };
  924. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  925. * descriptor, and report success or failure. */
  926. static int
  927. handle_control_postdescriptor(control_connection_t *conn,
  928. const control_cmd_args_t *args)
  929. {
  930. const char *msg=NULL;
  931. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  932. int cache = 0; /* eventually, we may switch this to 1 */
  933. const config_line_t *line;
  934. line = config_line_find_case(args->kwargs, "purpose");
  935. if (line) {
  936. purpose = router_purpose_from_string(line->value);
  937. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  938. control_printf_endreply(conn, 552, "Unknown purpose \"%s\"",
  939. line->value);
  940. goto done;
  941. }
  942. }
  943. line = config_line_find_case(args->kwargs, "cache");
  944. if (line) {
  945. if (!strcasecmp(line->value, "no"))
  946. cache = 0;
  947. else if (!strcasecmp(line->value, "yes"))
  948. cache = 1;
  949. else {
  950. control_printf_endreply(conn, 552, "Unknown cache request \"%s\"",
  951. line->value);
  952. goto done;
  953. }
  954. }
  955. switch (router_load_single_router(args->cmddata, purpose, cache, &msg)) {
  956. case -1:
  957. if (!msg) msg = "Could not parse descriptor";
  958. control_write_endreply(conn, 554, msg);
  959. break;
  960. case 0:
  961. if (!msg) msg = "Descriptor not added";
  962. control_write_endreply(conn, 251, msg);
  963. break;
  964. case 1:
  965. send_control_done(conn);
  966. break;
  967. }
  968. done:
  969. return 0;
  970. }
  971. static const control_cmd_syntax_t redirectstream_syntax = {
  972. .min_args = 2,
  973. .max_args = UINT_MAX, // XXX should be 3.
  974. };
  975. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  976. * address of the named AP stream, and report success or failure. */
  977. static int
  978. handle_control_redirectstream(control_connection_t *conn,
  979. const control_cmd_args_t *cmd_args)
  980. {
  981. entry_connection_t *ap_conn = NULL;
  982. char *new_addr = NULL;
  983. uint16_t new_port = 0;
  984. const smartlist_t *args = cmd_args->args;
  985. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  986. || !ap_conn->socks_request) {
  987. control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
  988. (char*)smartlist_get(args, 0));
  989. } else {
  990. int ok = 1;
  991. if (smartlist_len(args) > 2) { /* they included a port too */
  992. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  993. 10, 1, 65535, &ok, NULL);
  994. }
  995. if (!ok) {
  996. control_printf_endreply(conn, 512, "Cannot parse port \"%s\"",
  997. (char*)smartlist_get(args, 2));
  998. } else {
  999. new_addr = tor_strdup(smartlist_get(args, 1));
  1000. }
  1001. }
  1002. if (!new_addr)
  1003. return 0;
  1004. strlcpy(ap_conn->socks_request->address, new_addr,
  1005. sizeof(ap_conn->socks_request->address));
  1006. if (new_port)
  1007. ap_conn->socks_request->port = new_port;
  1008. tor_free(new_addr);
  1009. send_control_done(conn);
  1010. return 0;
  1011. }
  1012. static const control_cmd_syntax_t closestream_syntax = {
  1013. .min_args = 2,
  1014. .max_args = UINT_MAX, /* XXXX This is the original behavior, but
  1015. * maybe we should change the spec. */
  1016. };
  1017. /** Called when we get a CLOSESTREAM command; try to close the named stream
  1018. * and report success or failure. */
  1019. static int
  1020. handle_control_closestream(control_connection_t *conn,
  1021. const control_cmd_args_t *cmd_args)
  1022. {
  1023. entry_connection_t *ap_conn=NULL;
  1024. uint8_t reason=0;
  1025. int ok;
  1026. const smartlist_t *args = cmd_args->args;
  1027. tor_assert(smartlist_len(args) >= 2);
  1028. if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  1029. control_printf_endreply(conn, 552, "Unknown stream \"%s\"",
  1030. (char*)smartlist_get(args, 0));
  1031. else {
  1032. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  1033. &ok, NULL);
  1034. if (!ok) {
  1035. control_printf_endreply(conn, 552, "Unrecognized reason \"%s\"",
  1036. (char*)smartlist_get(args, 1));
  1037. ap_conn = NULL;
  1038. }
  1039. }
  1040. if (!ap_conn)
  1041. return 0;
  1042. connection_mark_unattached_ap(ap_conn, reason);
  1043. send_control_done(conn);
  1044. return 0;
  1045. }
  1046. static const control_cmd_syntax_t closecircuit_syntax = {
  1047. .min_args=1, .max_args=1,
  1048. .accept_keywords=true,
  1049. .kvline_flags=KV_OMIT_VALS,
  1050. // XXXX we might want to exclude unrecognized flags, but for now we
  1051. // XXXX just ignore them for backward compatibility.
  1052. };
  1053. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  1054. * and report success or failure. */
  1055. static int
  1056. handle_control_closecircuit(control_connection_t *conn,
  1057. const control_cmd_args_t *args)
  1058. {
  1059. const char *circ_id = smartlist_get(args->args, 0);
  1060. origin_circuit_t *circ = NULL;
  1061. if (!(circ=get_circ(circ_id))) {
  1062. control_printf_endreply(conn, 552, "Unknown circuit \"%s\"", circ_id);
  1063. return 0;
  1064. }
  1065. bool safe = config_lines_contain_flag(args->kwargs, "IfUnused");
  1066. if (!safe || !circ->p_streams) {
  1067. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  1068. }
  1069. send_control_done(conn);
  1070. return 0;
  1071. }
  1072. static const control_cmd_syntax_t resolve_syntax = {
  1073. .max_args=0,
  1074. .accept_keywords=true,
  1075. .kvline_flags=KV_OMIT_VALS,
  1076. };
  1077. /** Called when we get a RESOLVE command: start trying to resolve
  1078. * the listed addresses. */
  1079. static int
  1080. handle_control_resolve(control_connection_t *conn,
  1081. const control_cmd_args_t *args)
  1082. {
  1083. smartlist_t *failed;
  1084. int is_reverse = 0;
  1085. if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
  1086. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  1087. "isn't listening for ADDRMAP events. It probably won't see "
  1088. "the answer.");
  1089. }
  1090. {
  1091. const config_line_t *modearg = config_line_find_case(args->kwargs, "mode");
  1092. if (modearg && !strcasecmp(modearg->value, "reverse"))
  1093. is_reverse = 1;
  1094. }
  1095. failed = smartlist_new();
  1096. for (const config_line_t *line = args->kwargs; line; line = line->next) {
  1097. if (!strlen(line->value)) {
  1098. const char *addr = line->key;
  1099. if (dnsserv_launch_request(addr, is_reverse, conn)<0)
  1100. smartlist_add(failed, (char*)addr);
  1101. } else {
  1102. // XXXX arguably we should reject unrecognized keyword arguments,
  1103. // XXXX but the old implementation didn't do that.
  1104. }
  1105. }
  1106. send_control_done(conn);
  1107. SMARTLIST_FOREACH(failed, const char *, arg, {
  1108. control_event_address_mapped(arg, arg, time(NULL),
  1109. "internal", 0);
  1110. });
  1111. smartlist_free(failed);
  1112. return 0;
  1113. }
  1114. static const control_cmd_syntax_t protocolinfo_syntax = {
  1115. .max_args = UINT_MAX
  1116. };
  1117. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  1118. static int
  1119. handle_control_protocolinfo(control_connection_t *conn,
  1120. const control_cmd_args_t *cmd_args)
  1121. {
  1122. const char *bad_arg = NULL;
  1123. const smartlist_t *args = cmd_args->args;
  1124. conn->have_sent_protocolinfo = 1;
  1125. SMARTLIST_FOREACH(args, const char *, arg, {
  1126. int ok;
  1127. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  1128. if (!ok) {
  1129. bad_arg = arg;
  1130. break;
  1131. }
  1132. });
  1133. if (bad_arg) {
  1134. control_printf_endreply(conn, 513, "No such version %s",
  1135. escaped(bad_arg));
  1136. /* Don't tolerate bad arguments when not authenticated. */
  1137. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  1138. connection_mark_for_close(TO_CONN(conn));
  1139. goto done;
  1140. } else {
  1141. const or_options_t *options = get_options();
  1142. int cookies = options->CookieAuthentication;
  1143. char *cfile = get_controller_cookie_file_name();
  1144. char *abs_cfile;
  1145. char *esc_cfile;
  1146. char *methods;
  1147. abs_cfile = make_path_absolute(cfile);
  1148. esc_cfile = esc_for_log(abs_cfile);
  1149. {
  1150. int passwd = (options->HashedControlPassword != NULL ||
  1151. options->HashedControlSessionPassword != NULL);
  1152. smartlist_t *mlist = smartlist_new();
  1153. if (cookies) {
  1154. smartlist_add(mlist, (char*)"COOKIE");
  1155. smartlist_add(mlist, (char*)"SAFECOOKIE");
  1156. }
  1157. if (passwd)
  1158. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  1159. if (!cookies && !passwd)
  1160. smartlist_add(mlist, (char*)"NULL");
  1161. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  1162. smartlist_free(mlist);
  1163. }
  1164. control_write_midreply(conn, 250, "PROTOCOLINFO 1");
  1165. control_printf_midreply(conn, 250, "AUTH METHODS=%s%s%s", methods,
  1166. cookies?" COOKIEFILE=":"",
  1167. cookies?esc_cfile:"");
  1168. control_printf_midreply(conn, 250, "VERSION Tor=%s", escaped(VERSION));
  1169. send_control_done(conn);
  1170. tor_free(methods);
  1171. tor_free(cfile);
  1172. tor_free(abs_cfile);
  1173. tor_free(esc_cfile);
  1174. }
  1175. done:
  1176. return 0;
  1177. }
  1178. static const control_cmd_syntax_t usefeature_syntax = {
  1179. .max_args = UINT_MAX
  1180. };
  1181. /** Called when we get a USEFEATURE command: parse the feature list, and
  1182. * set up the control_connection's options properly. */
  1183. static int
  1184. handle_control_usefeature(control_connection_t *conn,
  1185. const control_cmd_args_t *cmd_args)
  1186. {
  1187. const smartlist_t *args = cmd_args->args;
  1188. int bad = 0;
  1189. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  1190. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  1191. ;
  1192. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  1193. ;
  1194. else {
  1195. control_printf_endreply(conn, 552, "Unrecognized feature \"%s\"",
  1196. arg);
  1197. bad = 1;
  1198. break;
  1199. }
  1200. } SMARTLIST_FOREACH_END(arg);
  1201. if (!bad) {
  1202. send_control_done(conn);
  1203. }
  1204. return 0;
  1205. }
  1206. static const control_cmd_syntax_t dropguards_syntax = {
  1207. .max_args = 0,
  1208. };
  1209. /** Implementation for the DROPGUARDS command. */
  1210. static int
  1211. handle_control_dropguards(control_connection_t *conn,
  1212. const control_cmd_args_t *args)
  1213. {
  1214. (void) args; /* We don't take arguments. */
  1215. static int have_warned = 0;
  1216. if (! have_warned) {
  1217. log_warn(LD_CONTROL, "DROPGUARDS is dangerous; make sure you understand "
  1218. "the risks before using it. It may be removed in a future "
  1219. "version of Tor.");
  1220. have_warned = 1;
  1221. }
  1222. remove_all_entry_guards();
  1223. send_control_done(conn);
  1224. return 0;
  1225. }
  1226. static const char *hsfetch_keywords[] = {
  1227. "SERVER", NULL,
  1228. };
  1229. static const control_cmd_syntax_t hsfetch_syntax = {
  1230. .min_args = 1, .max_args = 1,
  1231. .accept_keywords = true,
  1232. .allowed_keywords = hsfetch_keywords,
  1233. };
  1234. /** Implementation for the HSFETCH command. */
  1235. static int
  1236. handle_control_hsfetch(control_connection_t *conn,
  1237. const control_cmd_args_t *args)
  1238. {
  1239. char digest[DIGEST_LEN], *desc_id = NULL;
  1240. smartlist_t *hsdirs = NULL;
  1241. static const char *v2_str = "v2-";
  1242. const size_t v2_str_len = strlen(v2_str);
  1243. rend_data_t *rend_query = NULL;
  1244. ed25519_public_key_t v3_pk;
  1245. uint32_t version;
  1246. const char *hsaddress = NULL;
  1247. /* Extract the first argument (either HSAddress or DescID). */
  1248. const char *arg1 = smartlist_get(args->args, 0);
  1249. /* Test if it's an HS address without the .onion part. */
  1250. if (rend_valid_v2_service_id(arg1)) {
  1251. hsaddress = arg1;
  1252. version = HS_VERSION_TWO;
  1253. } else if (strcmpstart(arg1, v2_str) == 0 &&
  1254. rend_valid_descriptor_id(arg1 + v2_str_len) &&
  1255. base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
  1256. REND_DESC_ID_V2_LEN_BASE32) ==
  1257. REND_DESC_ID_V2_LEN_BASE32) {
  1258. /* We have a well formed version 2 descriptor ID. Keep the decoded value
  1259. * of the id. */
  1260. desc_id = digest;
  1261. version = HS_VERSION_TWO;
  1262. } else if (hs_address_is_valid(arg1)) {
  1263. hsaddress = arg1;
  1264. version = HS_VERSION_THREE;
  1265. hs_parse_address(hsaddress, &v3_pk, NULL, NULL);
  1266. } else {
  1267. control_printf_endreply(conn, 513, "Invalid argument \"%s\"", arg1);
  1268. goto done;
  1269. }
  1270. for (const config_line_t *line = args->kwargs; line; line = line->next) {
  1271. if (!strcasecmp(line->key, "SERVER")) {
  1272. const char *server = line->value;
  1273. const node_t *node = node_get_by_hex_id(server, 0);
  1274. if (!node) {
  1275. control_printf_endreply(conn, 552, "Server \"%s\" not found", server);
  1276. goto done;
  1277. }
  1278. if (!hsdirs) {
  1279. /* Stores routerstatus_t cmddata for each specified server. */
  1280. hsdirs = smartlist_new();
  1281. }
  1282. /* Valid server, add it to our local list. */
  1283. smartlist_add(hsdirs, node->rs);
  1284. } else {
  1285. tor_assert_nonfatal_unreached();
  1286. }
  1287. }
  1288. if (version == HS_VERSION_TWO) {
  1289. rend_query = rend_data_client_create(hsaddress, desc_id, NULL,
  1290. REND_NO_AUTH);
  1291. if (rend_query == NULL) {
  1292. control_write_endreply(conn, 551, "Error creating the HS query");
  1293. goto done;
  1294. }
  1295. }
  1296. /* Using a descriptor ID, we force the user to provide at least one
  1297. * hsdir server using the SERVER= option. */
  1298. if (desc_id && (!hsdirs || !smartlist_len(hsdirs))) {
  1299. control_write_endreply(conn, 512, "SERVER option is required");
  1300. goto done;
  1301. }
  1302. /* We are about to trigger HSDir fetch so send the OK now because after
  1303. * that 650 event(s) are possible so better to have the 250 OK before them
  1304. * to avoid out of order replies. */
  1305. send_control_done(conn);
  1306. /* Trigger the fetch using the built rend query and possibly a list of HS
  1307. * directory to use. This function ignores the client cache thus this will
  1308. * always send a fetch command. */
  1309. if (version == HS_VERSION_TWO) {
  1310. rend_client_fetch_v2_desc(rend_query, hsdirs);
  1311. } else if (version == HS_VERSION_THREE) {
  1312. hs_control_hsfetch_command(&v3_pk, hsdirs);
  1313. }
  1314. done:
  1315. /* Contains data pointer that we don't own thus no cleanup. */
  1316. smartlist_free(hsdirs);
  1317. rend_data_free(rend_query);
  1318. return 0;
  1319. }
  1320. static const char *hspost_keywords[] = {
  1321. "SERVER", "HSADDRESS", NULL
  1322. };
  1323. static const control_cmd_syntax_t hspost_syntax = {
  1324. .min_args = 0, .max_args = 0,
  1325. .accept_keywords = true,
  1326. .want_cmddata = true,
  1327. .allowed_keywords = hspost_keywords
  1328. };
  1329. /** Implementation for the HSPOST command. */
  1330. static int
  1331. handle_control_hspost(control_connection_t *conn,
  1332. const control_cmd_args_t *args)
  1333. {
  1334. smartlist_t *hs_dirs = NULL;
  1335. const char *encoded_desc = args->cmddata;
  1336. size_t encoded_desc_len = args->cmddata_len;
  1337. const char *onion_address = NULL;
  1338. const config_line_t *line;
  1339. for (line = args->kwargs; line; line = line->next) {
  1340. if (!strcasecmpstart(line->key, "SERVER")) {
  1341. const char *server = line->value;
  1342. const node_t *node = node_get_by_hex_id(server, 0);
  1343. if (!node || !node->rs) {
  1344. control_printf_endreply(conn, 552, "Server \"%s\" not found",
  1345. server);
  1346. goto done;
  1347. }
  1348. /* Valid server, add it to our local list. */
  1349. if (!hs_dirs)
  1350. hs_dirs = smartlist_new();
  1351. smartlist_add(hs_dirs, node->rs);
  1352. } else if (!strcasecmpstart(line->key, "HSADDRESS")) {
  1353. const char *address = line->value;
  1354. if (!hs_address_is_valid(address)) {
  1355. control_write_endreply(conn, 512, "Malformed onion address");
  1356. goto done;
  1357. }
  1358. onion_address = address;
  1359. } else {
  1360. tor_assert_nonfatal_unreached();
  1361. }
  1362. }
  1363. /* Handle the v3 case. */
  1364. if (onion_address) {
  1365. if (hs_control_hspost_command(encoded_desc, onion_address, hs_dirs) < 0) {
  1366. control_write_endreply(conn, 554, "Invalid descriptor");
  1367. } else {
  1368. send_control_done(conn);
  1369. }
  1370. goto done;
  1371. }
  1372. /* From this point on, it is only v2. */
  1373. /* parse it. */
  1374. rend_encoded_v2_service_descriptor_t *desc =
  1375. tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
  1376. desc->desc_str = tor_memdup_nulterm(encoded_desc, encoded_desc_len);
  1377. rend_service_descriptor_t *parsed = NULL;
  1378. char *intro_content = NULL;
  1379. size_t intro_size;
  1380. size_t encoded_size;
  1381. const char *next_desc;
  1382. if (!rend_parse_v2_service_descriptor(&parsed, desc->desc_id, &intro_content,
  1383. &intro_size, &encoded_size,
  1384. &next_desc, desc->desc_str, 1)) {
  1385. /* Post the descriptor. */
  1386. char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
  1387. if (!rend_get_service_id(parsed->pk, serviceid)) {
  1388. smartlist_t *descs = smartlist_new();
  1389. smartlist_add(descs, desc);
  1390. /* We are about to trigger HS descriptor upload so send the OK now
  1391. * because after that 650 event(s) are possible so better to have the
  1392. * 250 OK before them to avoid out of order replies. */
  1393. send_control_done(conn);
  1394. /* Trigger the descriptor upload */
  1395. directory_post_to_hs_dir(parsed, descs, hs_dirs, serviceid, 0);
  1396. smartlist_free(descs);
  1397. }
  1398. rend_service_descriptor_free(parsed);
  1399. } else {
  1400. control_write_endreply(conn, 554, "Invalid descriptor");
  1401. }
  1402. tor_free(intro_content);
  1403. rend_encoded_v2_service_descriptor_free(desc);
  1404. done:
  1405. smartlist_free(hs_dirs); /* Contents belong to the rend service code. */
  1406. return 0;
  1407. }
  1408. /* Helper function for ADD_ONION that adds an ephemeral service depending on
  1409. * the given hs_version.
  1410. *
  1411. * The secret key in pk depends on the hs_version. The ownership of the key
  1412. * used in pk is given to the HS subsystem so the caller must stop accessing
  1413. * it after.
  1414. *
  1415. * The port_cfgs is a list of service port. Ownership transferred to service.
  1416. * The max_streams refers to the MaxStreams= key.
  1417. * The max_streams_close_circuit refers to the MaxStreamsCloseCircuit key.
  1418. * The auth_type is the authentication type of the clients in auth_clients.
  1419. * The ownership of that list is transferred to the service.
  1420. *
  1421. * On success (RSAE_OKAY), the address_out points to a newly allocated string
  1422. * containing the onion address without the .onion part. On error, address_out
  1423. * is untouched. */
  1424. static hs_service_add_ephemeral_status_t
  1425. add_onion_helper_add_service(int hs_version,
  1426. add_onion_secret_key_t *pk,
  1427. smartlist_t *port_cfgs, int max_streams,
  1428. int max_streams_close_circuit, int auth_type,
  1429. smartlist_t *auth_clients, char **address_out)
  1430. {
  1431. hs_service_add_ephemeral_status_t ret;
  1432. tor_assert(pk);
  1433. tor_assert(port_cfgs);
  1434. tor_assert(address_out);
  1435. switch (hs_version) {
  1436. case HS_VERSION_TWO:
  1437. ret = rend_service_add_ephemeral(pk->v2, port_cfgs, max_streams,
  1438. max_streams_close_circuit, auth_type,
  1439. auth_clients, address_out);
  1440. break;
  1441. case HS_VERSION_THREE:
  1442. ret = hs_service_add_ephemeral(pk->v3, port_cfgs, max_streams,
  1443. max_streams_close_circuit, address_out);
  1444. break;
  1445. default:
  1446. tor_assert_unreached();
  1447. }
  1448. return ret;
  1449. }
  1450. /** The list of onion services that have been added via ADD_ONION that do not
  1451. * belong to any particular control connection.
  1452. */
  1453. static smartlist_t *detached_onion_services = NULL;
  1454. /**
  1455. * Return a list of detached onion services, or NULL if none exist.
  1456. **/
  1457. smartlist_t *
  1458. get_detached_onion_services(void)
  1459. {
  1460. return detached_onion_services;
  1461. }
  1462. static const char *add_onion_keywords[] = {
  1463. "Port", "Flags", "MaxStreams", "ClientAuth", NULL
  1464. };
  1465. static const control_cmd_syntax_t add_onion_syntax = {
  1466. .min_args = 1, .max_args = 1,
  1467. .accept_keywords = true,
  1468. .allowed_keywords = add_onion_keywords
  1469. };
  1470. /** Called when we get a ADD_ONION command; parse the body, and set up
  1471. * the new ephemeral Onion Service. */
  1472. static int
  1473. handle_control_add_onion(control_connection_t *conn,
  1474. const control_cmd_args_t *args)
  1475. {
  1476. /* Parse all of the arguments that do not involve handling cryptographic
  1477. * material first, since there's no reason to touch that at all if any of
  1478. * the other arguments are malformed.
  1479. */
  1480. smartlist_t *port_cfgs = smartlist_new();
  1481. smartlist_t *auth_clients = NULL;
  1482. smartlist_t *auth_created_clients = NULL;
  1483. int discard_pk = 0;
  1484. int detach = 0;
  1485. int max_streams = 0;
  1486. int max_streams_close_circuit = 0;
  1487. rend_auth_type_t auth_type = REND_NO_AUTH;
  1488. int non_anonymous = 0;
  1489. const config_line_t *arg;
  1490. for (arg = args->kwargs; arg; arg = arg->next) {
  1491. if (!strcasecmp(arg->key, "Port")) {
  1492. /* "Port=VIRTPORT[,TARGET]". */
  1493. rend_service_port_config_t *cfg =
  1494. rend_service_parse_port_config(arg->value, ",", NULL);
  1495. if (!cfg) {
  1496. control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
  1497. goto out;
  1498. }
  1499. smartlist_add(port_cfgs, cfg);
  1500. } else if (!strcasecmp(arg->key, "MaxStreams")) {
  1501. /* "MaxStreams=[0..65535]". */
  1502. int ok = 0;
  1503. max_streams = (int)tor_parse_long(arg->value, 10, 0, 65535, &ok, NULL);
  1504. if (!ok) {
  1505. control_write_endreply(conn, 512, "Invalid MaxStreams");
  1506. goto out;
  1507. }
  1508. } else if (!strcasecmp(arg->key, "Flags")) {
  1509. /* "Flags=Flag[,Flag]", where Flag can be:
  1510. * * 'DiscardPK' - If tor generates the keypair, do not include it in
  1511. * the response.
  1512. * * 'Detach' - Do not tie this onion service to any particular control
  1513. * connection.
  1514. * * 'MaxStreamsCloseCircuit' - Close the circuit if MaxStreams is
  1515. * exceeded.
  1516. * * 'BasicAuth' - Client authorization using the 'basic' method.
  1517. * * 'NonAnonymous' - Add a non-anonymous Single Onion Service. If this
  1518. * flag is present, tor must be in non-anonymous
  1519. * hidden service mode. If this flag is absent,
  1520. * tor must be in anonymous hidden service mode.
  1521. */
  1522. static const char *discard_flag = "DiscardPK";
  1523. static const char *detach_flag = "Detach";
  1524. static const char *max_s_close_flag = "MaxStreamsCloseCircuit";
  1525. static const char *basicauth_flag = "BasicAuth";
  1526. static const char *non_anonymous_flag = "NonAnonymous";
  1527. smartlist_t *flags = smartlist_new();
  1528. int bad = 0;
  1529. smartlist_split_string(flags, arg->value, ",", SPLIT_IGNORE_BLANK, 0);
  1530. if (smartlist_len(flags) < 1) {
  1531. control_write_endreply(conn, 512, "Invalid 'Flags' argument");
  1532. bad = 1;
  1533. }
  1534. SMARTLIST_FOREACH_BEGIN(flags, const char *, flag)
  1535. {
  1536. if (!strcasecmp(flag, discard_flag)) {
  1537. discard_pk = 1;
  1538. } else if (!strcasecmp(flag, detach_flag)) {
  1539. detach = 1;
  1540. } else if (!strcasecmp(flag, max_s_close_flag)) {
  1541. max_streams_close_circuit = 1;
  1542. } else if (!strcasecmp(flag, basicauth_flag)) {
  1543. auth_type = REND_BASIC_AUTH;
  1544. } else if (!strcasecmp(flag, non_anonymous_flag)) {
  1545. non_anonymous = 1;
  1546. } else {
  1547. control_printf_endreply(conn, 512, "Invalid 'Flags' argument: %s",
  1548. escaped(flag));
  1549. bad = 1;
  1550. break;
  1551. }
  1552. } SMARTLIST_FOREACH_END(flag);
  1553. SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
  1554. smartlist_free(flags);
  1555. if (bad)
  1556. goto out;
  1557. } else if (!strcasecmp(arg->key, "ClientAuth")) {
  1558. int created = 0;
  1559. rend_authorized_client_t *client =
  1560. add_onion_helper_clientauth(arg->value, &created, conn);
  1561. if (!client) {
  1562. goto out;
  1563. }
  1564. if (auth_clients != NULL) {
  1565. int bad = 0;
  1566. SMARTLIST_FOREACH_BEGIN(auth_clients, rend_authorized_client_t *, ac) {
  1567. if (strcmp(ac->client_name, client->client_name) == 0) {
  1568. bad = 1;
  1569. break;
  1570. }
  1571. } SMARTLIST_FOREACH_END(ac);
  1572. if (bad) {
  1573. control_write_endreply(conn, 512, "Duplicate name in ClientAuth");
  1574. rend_authorized_client_free(client);
  1575. goto out;
  1576. }
  1577. } else {
  1578. auth_clients = smartlist_new();
  1579. auth_created_clients = smartlist_new();
  1580. }
  1581. smartlist_add(auth_clients, client);
  1582. if (created) {
  1583. smartlist_add(auth_created_clients, client);
  1584. }
  1585. } else {
  1586. tor_assert_nonfatal_unreached();
  1587. goto out;
  1588. }
  1589. }
  1590. if (smartlist_len(port_cfgs) == 0) {
  1591. control_write_endreply(conn, 512, "Missing 'Port' argument");
  1592. goto out;
  1593. } else if (auth_type == REND_NO_AUTH && auth_clients != NULL) {
  1594. control_write_endreply(conn, 512, "No auth type specified");
  1595. goto out;
  1596. } else if (auth_type != REND_NO_AUTH && auth_clients == NULL) {
  1597. control_write_endreply(conn, 512, "No auth clients specified");
  1598. goto out;
  1599. } else if ((auth_type == REND_BASIC_AUTH &&
  1600. smartlist_len(auth_clients) > 512) ||
  1601. (auth_type == REND_STEALTH_AUTH &&
  1602. smartlist_len(auth_clients) > 16)) {
  1603. control_write_endreply(conn, 512, "Too many auth clients");
  1604. goto out;
  1605. } else if (non_anonymous != rend_service_non_anonymous_mode_enabled(
  1606. get_options())) {
  1607. /* If we failed, and the non-anonymous flag is set, Tor must be in
  1608. * anonymous hidden service mode.
  1609. * The error message changes based on the current Tor config:
  1610. * 512 Tor is in anonymous hidden service mode
  1611. * 512 Tor is in non-anonymous hidden service mode
  1612. * (I've deliberately written them out in full here to aid searchability.)
  1613. */
  1614. control_printf_endreply(conn, 512,
  1615. "Tor is in %sanonymous hidden service " "mode",
  1616. non_anonymous ? "" : "non-");
  1617. goto out;
  1618. }
  1619. /* Parse the "keytype:keyblob" argument. */
  1620. int hs_version = 0;
  1621. add_onion_secret_key_t pk = { NULL };
  1622. const char *key_new_alg = NULL;
  1623. char *key_new_blob = NULL;
  1624. const char *onionkey = smartlist_get(args->args, 0);
  1625. if (add_onion_helper_keyarg(onionkey, discard_pk,
  1626. &key_new_alg, &key_new_blob, &pk, &hs_version,
  1627. conn) < 0) {
  1628. goto out;
  1629. }
  1630. /* Hidden service version 3 don't have client authentication support so if
  1631. * ClientAuth was given, send back an error. */
  1632. if (hs_version == HS_VERSION_THREE && auth_clients) {
  1633. control_write_endreply(conn, 513, "ClientAuth not supported");
  1634. goto out;
  1635. }
  1636. /* Create the HS, using private key pk, client authentication auth_type,
  1637. * the list of auth_clients, and port config port_cfg.
  1638. * rend_service_add_ephemeral() will take ownership of pk and port_cfg,
  1639. * regardless of success/failure.
  1640. */
  1641. char *service_id = NULL;
  1642. int ret = add_onion_helper_add_service(hs_version, &pk, port_cfgs,
  1643. max_streams,
  1644. max_streams_close_circuit, auth_type,
  1645. auth_clients, &service_id);
  1646. port_cfgs = NULL; /* port_cfgs is now owned by the rendservice code. */
  1647. auth_clients = NULL; /* so is auth_clients */
  1648. switch (ret) {
  1649. case RSAE_OKAY:
  1650. {
  1651. if (detach) {
  1652. if (!detached_onion_services)
  1653. detached_onion_services = smartlist_new();
  1654. smartlist_add(detached_onion_services, service_id);
  1655. } else {
  1656. if (!conn->ephemeral_onion_services)
  1657. conn->ephemeral_onion_services = smartlist_new();
  1658. smartlist_add(conn->ephemeral_onion_services, service_id);
  1659. }
  1660. tor_assert(service_id);
  1661. control_printf_midreply(conn, 250, "ServiceID=%s", service_id);
  1662. if (key_new_alg) {
  1663. tor_assert(key_new_blob);
  1664. control_printf_midreply(conn, 250, "PrivateKey=%s:%s",
  1665. key_new_alg, key_new_blob);
  1666. }
  1667. if (auth_created_clients) {
  1668. SMARTLIST_FOREACH(auth_created_clients, rend_authorized_client_t *, ac, {
  1669. char *encoded = rend_auth_encode_cookie(ac->descriptor_cookie,
  1670. auth_type);
  1671. tor_assert(encoded);
  1672. control_printf_midreply(conn, 250, "ClientAuth=%s:%s",
  1673. ac->client_name, encoded);
  1674. memwipe(encoded, 0, strlen(encoded));
  1675. tor_free(encoded);
  1676. });
  1677. }
  1678. send_control_done(conn);
  1679. break;
  1680. }
  1681. case RSAE_BADPRIVKEY:
  1682. control_write_endreply(conn, 551, "Failed to generate onion address");
  1683. break;
  1684. case RSAE_ADDREXISTS:
  1685. control_write_endreply(conn, 550, "Onion address collision");
  1686. break;
  1687. case RSAE_BADVIRTPORT:
  1688. control_write_endreply(conn, 512, "Invalid VIRTPORT/TARGET");
  1689. break;
  1690. case RSAE_BADAUTH:
  1691. control_write_endreply(conn, 512, "Invalid client authorization");
  1692. break;
  1693. case RSAE_INTERNAL: /* FALLSTHROUGH */
  1694. default:
  1695. control_write_endreply(conn, 551, "Failed to add Onion Service");
  1696. }
  1697. if (key_new_blob) {
  1698. memwipe(key_new_blob, 0, strlen(key_new_blob));
  1699. tor_free(key_new_blob);
  1700. }
  1701. out:
  1702. if (port_cfgs) {
  1703. SMARTLIST_FOREACH(port_cfgs, rend_service_port_config_t*, p,
  1704. rend_service_port_config_free(p));
  1705. smartlist_free(port_cfgs);
  1706. }
  1707. if (auth_clients) {
  1708. SMARTLIST_FOREACH(auth_clients, rend_authorized_client_t *, ac,
  1709. rend_authorized_client_free(ac));
  1710. smartlist_free(auth_clients);
  1711. }
  1712. if (auth_created_clients) {
  1713. // Do not free entries; they are the same as auth_clients
  1714. smartlist_free(auth_created_clients);
  1715. }
  1716. return 0;
  1717. }
  1718. /** Helper function to handle parsing the KeyType:KeyBlob argument to the
  1719. * ADD_ONION command. Return a new crypto_pk_t and if a new key was generated
  1720. * and the private key not discarded, the algorithm and serialized private key,
  1721. * or NULL and an optional control protocol error message on failure. The
  1722. * caller is responsible for freeing the returned key_new_blob.
  1723. *
  1724. * Note: The error messages returned are deliberately vague to avoid echoing
  1725. * key material.
  1726. *
  1727. * Note: conn is only used for writing control replies. For testing
  1728. * purposes, it can be NULL if control_write_reply() is appropriately
  1729. * mocked.
  1730. */
  1731. STATIC int
  1732. add_onion_helper_keyarg(const char *arg, int discard_pk,
  1733. const char **key_new_alg_out, char **key_new_blob_out,
  1734. add_onion_secret_key_t *decoded_key, int *hs_version,
  1735. control_connection_t *conn)
  1736. {
  1737. smartlist_t *key_args = smartlist_new();
  1738. crypto_pk_t *pk = NULL;
  1739. const char *key_new_alg = NULL;
  1740. char *key_new_blob = NULL;
  1741. int ret = -1;
  1742. smartlist_split_string(key_args, arg, ":", SPLIT_IGNORE_BLANK, 0);
  1743. if (smartlist_len(key_args) != 2) {
  1744. control_write_endreply(conn, 512, "Invalid key type/blob");
  1745. goto err;
  1746. }
  1747. /* The format is "KeyType:KeyBlob". */
  1748. static const char *key_type_new = "NEW";
  1749. static const char *key_type_best = "BEST";
  1750. static const char *key_type_rsa1024 = "RSA1024";
  1751. static const char *key_type_ed25519_v3 = "ED25519-V3";
  1752. const char *key_type = smartlist_get(key_args, 0);
  1753. const char *key_blob = smartlist_get(key_args, 1);
  1754. if (!strcasecmp(key_type_rsa1024, key_type)) {
  1755. /* "RSA:<Base64 Blob>" - Loading a pre-existing RSA1024 key. */
  1756. pk = crypto_pk_base64_decode_private(key_blob, strlen(key_blob));
  1757. if (!pk) {
  1758. control_write_endreply(conn, 512, "Failed to decode RSA key");
  1759. goto err;
  1760. }
  1761. if (crypto_pk_num_bits(pk) != PK_BYTES*8) {
  1762. crypto_pk_free(pk);
  1763. control_write_endreply(conn, 512, "Invalid RSA key size");
  1764. goto err;
  1765. }
  1766. decoded_key->v2 = pk;
  1767. *hs_version = HS_VERSION_TWO;
  1768. } else if (!strcasecmp(key_type_ed25519_v3, key_type)) {
  1769. /* "ED25519-V3:<Base64 Blob>" - Loading a pre-existing ed25519 key. */
  1770. ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
  1771. if (base64_decode((char *) sk->seckey, sizeof(sk->seckey), key_blob,
  1772. strlen(key_blob)) != sizeof(sk->seckey)) {
  1773. tor_free(sk);
  1774. control_write_endreply(conn, 512, "Failed to decode ED25519-V3 key");
  1775. goto err;
  1776. }
  1777. decoded_key->v3 = sk;
  1778. *hs_version = HS_VERSION_THREE;
  1779. } else if (!strcasecmp(key_type_new, key_type)) {
  1780. /* "NEW:<Algorithm>" - Generating a new key, blob as algorithm. */
  1781. if (!strcasecmp(key_type_rsa1024, key_blob)) {
  1782. /* "RSA1024", RSA 1024 bit, also currently "BEST" by default. */
  1783. pk = crypto_pk_new();
  1784. if (crypto_pk_generate_key(pk)) {
  1785. control_printf_endreply(conn, 551, "Failed to generate %s key",
  1786. key_type_rsa1024);
  1787. goto err;
  1788. }
  1789. if (!discard_pk) {
  1790. if (crypto_pk_base64_encode_private(pk, &key_new_blob)) {
  1791. crypto_pk_free(pk);
  1792. control_printf_endreply(conn, 551, "Failed to encode %s key",
  1793. key_type_rsa1024);
  1794. goto err;
  1795. }
  1796. key_new_alg = key_type_rsa1024;
  1797. }
  1798. decoded_key->v2 = pk;
  1799. *hs_version = HS_VERSION_TWO;
  1800. } else if (!strcasecmp(key_type_ed25519_v3, key_blob) ||
  1801. !strcasecmp(key_type_best, key_blob)) {
  1802. /* "ED25519-V3", ed25519 key, also currently "BEST" by default. */
  1803. ed25519_secret_key_t *sk = tor_malloc_zero(sizeof(*sk));
  1804. if (ed25519_secret_key_generate(sk, 1) < 0) {
  1805. tor_free(sk);
  1806. control_printf_endreply(conn, 551, "Failed to generate %s key",
  1807. key_type_ed25519_v3);
  1808. goto err;
  1809. }
  1810. if (!discard_pk) {
  1811. ssize_t len = base64_encode_size(sizeof(sk->seckey), 0) + 1;
  1812. key_new_blob = tor_malloc_zero(len);
  1813. if (base64_encode(key_new_blob, len, (const char *) sk->seckey,
  1814. sizeof(sk->seckey), 0) != (len - 1)) {
  1815. tor_free(sk);
  1816. tor_free(key_new_blob);
  1817. control_printf_endreply(conn, 551, "Failed to encode %s key",
  1818. key_type_ed25519_v3);
  1819. goto err;
  1820. }
  1821. key_new_alg = key_type_ed25519_v3;
  1822. }
  1823. decoded_key->v3 = sk;
  1824. *hs_version = HS_VERSION_THREE;
  1825. } else {
  1826. control_write_endreply(conn, 513, "Invalid key type");
  1827. goto err;
  1828. }
  1829. } else {
  1830. control_write_endreply(conn, 513, "Invalid key type");
  1831. goto err;
  1832. }
  1833. /* Succeeded in loading or generating a private key. */
  1834. ret = 0;
  1835. err:
  1836. SMARTLIST_FOREACH(key_args, char *, cp, {
  1837. memwipe(cp, 0, strlen(cp));
  1838. tor_free(cp);
  1839. });
  1840. smartlist_free(key_args);
  1841. *key_new_alg_out = key_new_alg;
  1842. *key_new_blob_out = key_new_blob;
  1843. return ret;
  1844. }
  1845. /** Helper function to handle parsing a ClientAuth argument to the
  1846. * ADD_ONION command. Return a new rend_authorized_client_t, or NULL
  1847. * and an optional control protocol error message on failure. The
  1848. * caller is responsible for freeing the returned auth_client.
  1849. *
  1850. * If 'created' is specified, it will be set to 1 when a new cookie has
  1851. * been generated.
  1852. *
  1853. * Note: conn is only used for writing control replies. For testing
  1854. * purposes, it can be NULL if control_write_reply() is appropriately
  1855. * mocked.
  1856. */
  1857. STATIC rend_authorized_client_t *
  1858. add_onion_helper_clientauth(const char *arg, int *created,
  1859. control_connection_t *conn)
  1860. {
  1861. int ok = 0;
  1862. tor_assert(arg);
  1863. tor_assert(created);
  1864. smartlist_t *auth_args = smartlist_new();
  1865. rend_authorized_client_t *client =
  1866. tor_malloc_zero(sizeof(rend_authorized_client_t));
  1867. smartlist_split_string(auth_args, arg, ":", 0, 0);
  1868. if (smartlist_len(auth_args) < 1 || smartlist_len(auth_args) > 2) {
  1869. control_write_endreply(conn, 512, "Invalid ClientAuth syntax");
  1870. goto err;
  1871. }
  1872. client->client_name = tor_strdup(smartlist_get(auth_args, 0));
  1873. if (smartlist_len(auth_args) == 2) {
  1874. char *decode_err_msg = NULL;
  1875. if (rend_auth_decode_cookie(smartlist_get(auth_args, 1),
  1876. client->descriptor_cookie,
  1877. NULL, &decode_err_msg) < 0) {
  1878. tor_assert(decode_err_msg);
  1879. control_write_endreply(conn, 512, decode_err_msg);
  1880. tor_free(decode_err_msg);
  1881. goto err;
  1882. }
  1883. *created = 0;
  1884. } else {
  1885. crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
  1886. *created = 1;
  1887. }
  1888. if (!rend_valid_client_name(client->client_name)) {
  1889. control_write_endreply(conn, 512, "Invalid name in ClientAuth");
  1890. goto err;
  1891. }
  1892. ok = 1;
  1893. err:
  1894. SMARTLIST_FOREACH(auth_args, char *, item, tor_free(item));
  1895. smartlist_free(auth_args);
  1896. if (!ok) {
  1897. rend_authorized_client_free(client);
  1898. client = NULL;
  1899. }
  1900. return client;
  1901. }
  1902. static const control_cmd_syntax_t del_onion_syntax = {
  1903. .min_args = 1, .max_args = 1,
  1904. };
  1905. /** Called when we get a DEL_ONION command; parse the body, and remove
  1906. * the existing ephemeral Onion Service. */
  1907. static int
  1908. handle_control_del_onion(control_connection_t *conn,
  1909. const control_cmd_args_t *cmd_args)
  1910. {
  1911. int hs_version = 0;
  1912. smartlist_t *args = cmd_args->args;
  1913. tor_assert(smartlist_len(args) == 1);
  1914. const char *service_id = smartlist_get(args, 0);
  1915. if (rend_valid_v2_service_id(service_id)) {
  1916. hs_version = HS_VERSION_TWO;
  1917. } else if (hs_address_is_valid(service_id)) {
  1918. hs_version = HS_VERSION_THREE;
  1919. } else {
  1920. control_write_endreply(conn, 512, "Malformed Onion Service id");
  1921. goto out;
  1922. }
  1923. /* Determine if the onion service belongs to this particular control
  1924. * connection, or if it is in the global list of detached services. If it
  1925. * is in neither, either the service ID is invalid in some way, or it
  1926. * explicitly belongs to a different control connection, and an error
  1927. * should be returned.
  1928. */
  1929. smartlist_t *services[2] = {
  1930. conn->ephemeral_onion_services,
  1931. detached_onion_services
  1932. };
  1933. smartlist_t *onion_services = NULL;
  1934. int idx = -1;
  1935. for (size_t i = 0; i < ARRAY_LENGTH(services); i++) {
  1936. idx = smartlist_string_pos(services[i], service_id);
  1937. if (idx != -1) {
  1938. onion_services = services[i];
  1939. break;
  1940. }
  1941. }
  1942. if (onion_services == NULL) {
  1943. control_write_endreply(conn, 552, "Unknown Onion Service id");
  1944. } else {
  1945. int ret = -1;
  1946. switch (hs_version) {
  1947. case HS_VERSION_TWO:
  1948. ret = rend_service_del_ephemeral(service_id);
  1949. break;
  1950. case HS_VERSION_THREE:
  1951. ret = hs_service_del_ephemeral(service_id);
  1952. break;
  1953. default:
  1954. /* The ret value will be -1 thus hitting the warning below. This should
  1955. * never happen because of the check at the start of the function. */
  1956. break;
  1957. }
  1958. if (ret < 0) {
  1959. /* This should *NEVER* fail, since the service is on either the
  1960. * per-control connection list, or the global one.
  1961. */
  1962. log_warn(LD_BUG, "Failed to remove Onion Service %s.",
  1963. escaped(service_id));
  1964. tor_fragile_assert();
  1965. }
  1966. /* Remove/scrub the service_id from the appropriate list. */
  1967. char *cp = smartlist_get(onion_services, idx);
  1968. smartlist_del(onion_services, idx);
  1969. memwipe(cp, 0, strlen(cp));
  1970. tor_free(cp);
  1971. send_control_done(conn);
  1972. }
  1973. out:
  1974. return 0;
  1975. }
  1976. static const control_cmd_syntax_t obsolete_syntax = {
  1977. .max_args = UINT_MAX
  1978. };
  1979. /**
  1980. * Called when we get an obsolete command: tell the controller that it is
  1981. * obsolete.
  1982. */
  1983. static int
  1984. handle_control_obsolete(control_connection_t *conn,
  1985. const control_cmd_args_t *args)
  1986. {
  1987. (void)args;
  1988. char *command = tor_strdup(conn->current_cmd);
  1989. tor_strupper(command);
  1990. control_printf_endreply(conn, 511, "%s is obsolete.", command);
  1991. tor_free(command);
  1992. return 0;
  1993. }
  1994. /**
  1995. * Function pointer to a handler function for a controller command.
  1996. **/
  1997. typedef int (*handler_fn_t) (control_connection_t *conn,
  1998. const control_cmd_args_t *args);
  1999. /**
  2000. * Definition for a controller command.
  2001. */
  2002. typedef struct control_cmd_def_t {
  2003. /**
  2004. * The name of the command. If the command is multiline, the name must
  2005. * begin with "+". This is not case-sensitive. */
  2006. const char *name;
  2007. /**
  2008. * A function to execute the command.
  2009. */
  2010. handler_fn_t handler;
  2011. /**
  2012. * Zero or more CMD_FL_* flags, or'd together.
  2013. */
  2014. unsigned flags;
  2015. /**
  2016. * For parsed command: a syntax description.
  2017. */
  2018. const control_cmd_syntax_t *syntax;
  2019. } control_cmd_def_t;
  2020. /**
  2021. * Indicates that the command's arguments are sensitive, and should be
  2022. * memwiped after use.
  2023. */
  2024. #define CMD_FL_WIPE (1u<<0)
  2025. /** Macro: declare a command with a one-line argument, a given set of flags,
  2026. * and a syntax definition.
  2027. **/
  2028. #define ONE_LINE(name, flags) \
  2029. { \
  2030. #name, \
  2031. handle_control_ ##name, \
  2032. flags, \
  2033. &name##_syntax, \
  2034. }
  2035. /**
  2036. * Macro: declare a command with a multi-line argument and a given set of
  2037. * flags.
  2038. **/
  2039. #define MULTLINE(name, flags) \
  2040. { "+"#name, \
  2041. handle_control_ ##name, \
  2042. flags, \
  2043. &name##_syntax \
  2044. }
  2045. /**
  2046. * Macro: declare an obsolete command. (Obsolete commands give a different
  2047. * error than non-existent ones.)
  2048. **/
  2049. #define OBSOLETE(name) \
  2050. { #name, \
  2051. handle_control_obsolete, \
  2052. 0, \
  2053. &obsolete_syntax, \
  2054. }
  2055. /**
  2056. * An array defining all the recognized controller commands.
  2057. **/
  2058. static const control_cmd_def_t CONTROL_COMMANDS[] =
  2059. {
  2060. ONE_LINE(setconf, 0),
  2061. ONE_LINE(resetconf, 0),
  2062. ONE_LINE(getconf, 0),
  2063. MULTLINE(loadconf, 0),
  2064. ONE_LINE(setevents, 0),
  2065. ONE_LINE(authenticate, CMD_FL_WIPE),
  2066. ONE_LINE(saveconf, 0),
  2067. ONE_LINE(signal, 0),
  2068. ONE_LINE(takeownership, 0),
  2069. ONE_LINE(dropownership, 0),
  2070. ONE_LINE(mapaddress, 0),
  2071. ONE_LINE(getinfo, 0),
  2072. ONE_LINE(extendcircuit, 0),
  2073. ONE_LINE(setcircuitpurpose, 0),
  2074. OBSOLETE(setrouterpurpose),
  2075. ONE_LINE(attachstream, 0),
  2076. MULTLINE(postdescriptor, 0),
  2077. ONE_LINE(redirectstream, 0),
  2078. ONE_LINE(closestream, 0),
  2079. ONE_LINE(closecircuit, 0),
  2080. ONE_LINE(usefeature, 0),
  2081. ONE_LINE(resolve, 0),
  2082. ONE_LINE(protocolinfo, 0),
  2083. ONE_LINE(authchallenge, CMD_FL_WIPE),
  2084. ONE_LINE(dropguards, 0),
  2085. ONE_LINE(hsfetch, 0),
  2086. MULTLINE(hspost, 0),
  2087. ONE_LINE(add_onion, CMD_FL_WIPE),
  2088. ONE_LINE(del_onion, CMD_FL_WIPE),
  2089. };
  2090. /**
  2091. * The number of entries in CONTROL_COMMANDS.
  2092. **/
  2093. static const size_t N_CONTROL_COMMANDS = ARRAY_LENGTH(CONTROL_COMMANDS);
  2094. /**
  2095. * Run a single control command, as defined by a control_cmd_def_t,
  2096. * with a given set of arguments.
  2097. */
  2098. static int
  2099. handle_single_control_command(const control_cmd_def_t *def,
  2100. control_connection_t *conn,
  2101. uint32_t cmd_data_len,
  2102. char *args)
  2103. {
  2104. int rv = 0;
  2105. control_cmd_args_t *parsed_args;
  2106. char *err=NULL;
  2107. tor_assert(def->syntax);
  2108. parsed_args = control_cmd_parse_args(conn->current_cmd,
  2109. def->syntax,
  2110. cmd_data_len, args,
  2111. &err);
  2112. if (!parsed_args) {
  2113. control_printf_endreply(conn, 512, "Bad arguments to %s: %s",
  2114. conn->current_cmd, err?err:"");
  2115. tor_free(err);
  2116. } else {
  2117. if (BUG(err))
  2118. tor_free(err);
  2119. if (def->handler(conn, parsed_args))
  2120. rv = 0;
  2121. if (def->flags & CMD_FL_WIPE)
  2122. control_cmd_args_wipe(parsed_args);
  2123. control_cmd_args_free(parsed_args);
  2124. }
  2125. if (def->flags & CMD_FL_WIPE)
  2126. memwipe(args, 0, cmd_data_len);
  2127. return rv;
  2128. }
  2129. /**
  2130. * Run a given controller command, as selected by the current_cmd field of
  2131. * <b>conn</b>.
  2132. */
  2133. int
  2134. handle_control_command(control_connection_t *conn,
  2135. uint32_t cmd_data_len,
  2136. char *args)
  2137. {
  2138. tor_assert(conn);
  2139. tor_assert(args);
  2140. tor_assert(args[cmd_data_len] == '\0');
  2141. for (unsigned i = 0; i < N_CONTROL_COMMANDS; ++i) {
  2142. const control_cmd_def_t *def = &CONTROL_COMMANDS[i];
  2143. if (!strcasecmp(conn->current_cmd, def->name)) {
  2144. return handle_single_control_command(def, conn, cmd_data_len, args);
  2145. }
  2146. }
  2147. control_printf_endreply(conn, 510, "Unrecognized command \"%s\"",
  2148. conn->current_cmd);
  2149. return 0;
  2150. }
  2151. void
  2152. control_cmd_free_all(void)
  2153. {
  2154. if (detached_onion_services) { /* Free the detached onion services */
  2155. SMARTLIST_FOREACH(detached_onion_services, char *, cp, tor_free(cp));
  2156. smartlist_free(detached_onion_services);
  2157. }
  2158. }