control_cmd.c 75 KB

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