control_cmd.c 80 KB

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