control_cmd.c 75 KB

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