control_cmd.c 75 KB

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