control_cmd.c 76 KB

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