control_cmd.c 76 KB

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