main.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file main.c
  8. * \brief Invocation module. Initializes subsystems and runs the main loop.
  9. **/
  10. #include "core/or/or.h"
  11. #include "app/config/config.h"
  12. #include "app/config/statefile.h"
  13. #include "app/main/main.h"
  14. #include "app/main/ntmain.h"
  15. #include "app/main/subsysmgr.h"
  16. #include "core/mainloop/connection.h"
  17. #include "core/mainloop/cpuworker.h"
  18. #include "core/mainloop/mainloop.h"
  19. #include "core/mainloop/netstatus.h"
  20. #include "core/or/channel.h"
  21. #include "core/or/channelpadding.h"
  22. #include "core/or/circuitpadding.h"
  23. #include "core/or/channeltls.h"
  24. #include "core/or/circuitlist.h"
  25. #include "core/or/circuitmux_ewma.h"
  26. #include "core/or/command.h"
  27. #include "core/or/connection_edge.h"
  28. #include "core/or/connection_or.h"
  29. #include "core/or/dos.h"
  30. #include "core/or/policies.h"
  31. #include "core/or/protover.h"
  32. #include "core/or/relay.h"
  33. #include "core/or/scheduler.h"
  34. #include "core/or/status.h"
  35. #include "core/or/versions.h"
  36. #include "feature/api/tor_api.h"
  37. #include "feature/api/tor_api_internal.h"
  38. #include "feature/client/addressmap.h"
  39. #include "feature/client/bridges.h"
  40. #include "feature/client/entrynodes.h"
  41. #include "feature/client/transports.h"
  42. #include "feature/control/control.h"
  43. #include "feature/control/control_events.h"
  44. #include "feature/dirauth/bwauth.h"
  45. #include "feature/dirauth/keypin.h"
  46. #include "feature/dirauth/process_descs.h"
  47. #include "feature/dircache/consdiffmgr.h"
  48. #include "feature/dircache/dirserv.h"
  49. #include "feature/dirparse/routerparse.h"
  50. #include "feature/hibernate/hibernate.h"
  51. #include "feature/hs/hs_cache.h"
  52. #include "feature/nodelist/authcert.h"
  53. #include "feature/nodelist/microdesc.h"
  54. #include "feature/nodelist/networkstatus.h"
  55. #include "feature/nodelist/nodelist.h"
  56. #include "feature/nodelist/routerlist.h"
  57. #include "feature/relay/dns.h"
  58. #include "feature/relay/ext_orport.h"
  59. #include "feature/relay/onion_queue.h"
  60. #include "feature/relay/routerkeys.h"
  61. #include "feature/relay/routermode.h"
  62. #include "feature/rend/rendcache.h"
  63. #include "feature/rend/rendclient.h"
  64. #include "feature/rend/rendservice.h"
  65. #include "feature/stats/geoip_stats.h"
  66. #include "feature/stats/predict_ports.h"
  67. #include "feature/stats/rephist.h"
  68. #include "lib/compress/compress.h"
  69. #include "lib/buf/buffers.h"
  70. #include "lib/crypt_ops/crypto_rand.h"
  71. #include "lib/crypt_ops/crypto_s2k.h"
  72. #include "lib/geoip/geoip.h"
  73. #include "lib/net/resolve.h"
  74. #include "lib/process/waitpid.h"
  75. #include "lib/meminfo/meminfo.h"
  76. #include "lib/osinfo/uname.h"
  77. #include "lib/sandbox/sandbox.h"
  78. #include "lib/fs/lockfile.h"
  79. #include "lib/net/resolve.h"
  80. #include "lib/tls/tortls.h"
  81. #include "lib/evloop/compat_libevent.h"
  82. #include "lib/encoding/confline.h"
  83. #include "lib/evloop/timers.h"
  84. #include "lib/crypt_ops/crypto_init.h"
  85. #include "lib/version/torversion.h"
  86. #include <event2/event.h>
  87. #include "feature/dirauth/dirvote.h"
  88. #include "feature/dirauth/authmode.h"
  89. #include "feature/dirauth/shared_random.h"
  90. #include "core/or/or_connection_st.h"
  91. #include "core/or/port_cfg_st.h"
  92. #ifdef HAVE_UNISTD_H
  93. #include <unistd.h>
  94. #endif
  95. #ifdef HAVE_SYSTEMD
  96. # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
  97. /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
  98. * Coverity. Here's a kludge to unconfuse it.
  99. */
  100. # define __INCLUDE_LEVEL__ 2
  101. #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
  102. #include <systemd/sd-daemon.h>
  103. #endif /* defined(HAVE_SYSTEMD) */
  104. void evdns_shutdown(int);
  105. #ifdef HAVE_RUST
  106. // helper function defined in Rust to output a log message indicating if tor is
  107. // running with Rust enabled. See src/rust/tor_util
  108. void rust_log_welcome_string(void);
  109. #endif
  110. /********* PROTOTYPES **********/
  111. static void dumpmemusage(int severity);
  112. static void dumpstats(int severity); /* log stats */
  113. static void process_signal(int sig);
  114. /********* START VARIABLES **********/
  115. /** Decides our behavior when no logs are configured/before any
  116. * logs have been configured. For 0, we log notice to stdout as normal.
  117. * For 1, we log warnings only. For 2, we log nothing.
  118. */
  119. int quiet_level = 0;
  120. /********* END VARIABLES ************/
  121. /** Called when we get a SIGHUP: reload configuration files and keys,
  122. * retry all connections, and so on. */
  123. static int
  124. do_hup(void)
  125. {
  126. const or_options_t *options = get_options();
  127. log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config and "
  128. "resetting internal state.");
  129. if (accounting_is_enabled(options))
  130. accounting_record_bandwidth_usage(time(NULL), get_or_state());
  131. router_reset_warnings();
  132. routerlist_reset_warnings();
  133. /* first, reload config variables, in case they've changed */
  134. if (options->ReloadTorrcOnSIGHUP) {
  135. /* no need to provide argc/v, they've been cached in init_from_config */
  136. int init_rv = options_init_from_torrc(0, NULL);
  137. if (init_rv < 0) {
  138. log_err(LD_CONFIG,"Reading config failed--see warnings above. "
  139. "For usage, try -h.");
  140. return -1;
  141. } else if (BUG(init_rv > 0)) {
  142. // LCOV_EXCL_START
  143. /* This should be impossible: the only "return 1" cases in
  144. * options_init_from_torrc are ones caused by command-line arguments;
  145. * but they can't change while Tor is running. */
  146. return -1;
  147. // LCOV_EXCL_STOP
  148. }
  149. options = get_options(); /* they have changed now */
  150. /* Logs are only truncated the first time they are opened, but were
  151. probably intended to be cleaned up on signal. */
  152. if (options->TruncateLogFile)
  153. truncate_logs();
  154. } else {
  155. char *msg = NULL;
  156. log_notice(LD_GENERAL, "Not reloading config file: the controller told "
  157. "us not to.");
  158. /* Make stuff get rescanned, reloaded, etc. */
  159. if (set_options((or_options_t*)options, &msg) < 0) {
  160. if (!msg)
  161. msg = tor_strdup("Unknown error");
  162. log_warn(LD_GENERAL, "Unable to re-set previous options: %s", msg);
  163. tor_free(msg);
  164. }
  165. }
  166. if (authdir_mode(options)) {
  167. /* reload the approved-routers file */
  168. if (dirserv_load_fingerprint_file() < 0) {
  169. /* warnings are logged from dirserv_load_fingerprint_file() directly */
  170. log_info(LD_GENERAL, "Error reloading fingerprints. "
  171. "Continuing with old list.");
  172. }
  173. }
  174. /* Rotate away from the old dirty circuits. This has to be done
  175. * after we've read the new options, but before we start using
  176. * circuits for directory fetches. */
  177. circuit_mark_all_dirty_circs_as_unusable();
  178. /* retry appropriate downloads */
  179. router_reset_status_download_failures();
  180. router_reset_descriptor_download_failures();
  181. if (!net_is_disabled())
  182. update_networkstatus_downloads(time(NULL));
  183. /* We'll retry routerstatus downloads in about 10 seconds; no need to
  184. * force a retry there. */
  185. if (server_mode(options)) {
  186. /* Maybe we've been given a new ed25519 key or certificate?
  187. */
  188. time_t now = approx_time();
  189. int new_signing_key = load_ed_keys(options, now);
  190. if (new_signing_key < 0 ||
  191. generate_ed_link_cert(options, now, new_signing_key > 0)) {
  192. log_warn(LD_OR, "Problem reloading Ed25519 keys; still using old keys.");
  193. }
  194. /* Update cpuworker and dnsworker processes, so they get up-to-date
  195. * configuration options. */
  196. cpuworkers_rotate_keyinfo();
  197. dns_reset();
  198. }
  199. return 0;
  200. }
  201. /** Libevent callback: invoked when we get a signal.
  202. */
  203. static void
  204. signal_callback(evutil_socket_t fd, short events, void *arg)
  205. {
  206. const int *sigptr = arg;
  207. const int sig = *sigptr;
  208. (void)fd;
  209. (void)events;
  210. update_current_time(time(NULL));
  211. process_signal(sig);
  212. }
  213. /** Do the work of acting on a signal received in <b>sig</b> */
  214. static void
  215. process_signal(int sig)
  216. {
  217. switch (sig)
  218. {
  219. case SIGTERM:
  220. log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
  221. tor_shutdown_event_loop_and_exit(0);
  222. break;
  223. case SIGINT:
  224. if (!server_mode(get_options())) { /* do it now */
  225. log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
  226. tor_shutdown_event_loop_and_exit(0);
  227. return;
  228. }
  229. #ifdef HAVE_SYSTEMD
  230. sd_notify(0, "STOPPING=1");
  231. #endif
  232. hibernate_begin_shutdown();
  233. break;
  234. #ifdef SIGPIPE
  235. case SIGPIPE:
  236. log_debug(LD_GENERAL,"Caught SIGPIPE. Ignoring.");
  237. break;
  238. #endif
  239. case SIGUSR1:
  240. /* prefer to log it at INFO, but make sure we always see it */
  241. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  242. control_event_signal(sig);
  243. break;
  244. case SIGUSR2:
  245. switch_logs_debug();
  246. log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
  247. "Send HUP to change back.");
  248. control_event_signal(sig);
  249. break;
  250. case SIGHUP:
  251. #ifdef HAVE_SYSTEMD
  252. sd_notify(0, "RELOADING=1");
  253. #endif
  254. if (do_hup() < 0) {
  255. log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
  256. tor_shutdown_event_loop_and_exit(1);
  257. return;
  258. }
  259. #ifdef HAVE_SYSTEMD
  260. sd_notify(0, "READY=1");
  261. #endif
  262. control_event_signal(sig);
  263. break;
  264. #ifdef SIGCHLD
  265. case SIGCHLD:
  266. notify_pending_waitpid_callbacks();
  267. break;
  268. #endif
  269. case SIGNEWNYM: {
  270. do_signewnym(time(NULL));
  271. break;
  272. }
  273. case SIGCLEARDNSCACHE:
  274. addressmap_clear_transient();
  275. control_event_signal(sig);
  276. break;
  277. case SIGHEARTBEAT:
  278. log_heartbeat(time(NULL));
  279. control_event_signal(sig);
  280. break;
  281. case SIGACTIVE:
  282. /* "SIGACTIVE" counts as ersatz user activity. */
  283. note_user_activity(approx_time());
  284. control_event_signal(sig);
  285. break;
  286. case SIGDORMANT:
  287. /* "SIGDORMANT" means to ignore past user activity */
  288. log_notice(LD_GENERAL, "Going dormant because of controller request.");
  289. reset_user_activity(0);
  290. set_network_participation(false);
  291. schedule_rescan_periodic_events();
  292. control_event_signal(sig);
  293. break;
  294. }
  295. }
  296. /**
  297. * Write current memory usage information to the log.
  298. */
  299. static void
  300. dumpmemusage(int severity)
  301. {
  302. connection_dump_buffer_mem_stats(severity);
  303. tor_log(severity, LD_GENERAL, "In rephist: %"PRIu64" used by %d Tors.",
  304. (rephist_total_alloc), rephist_total_num);
  305. dump_routerlist_mem_usage(severity);
  306. dump_cell_pool_usage(severity);
  307. dump_dns_mem_usage(severity);
  308. tor_log_mallinfo(severity);
  309. }
  310. /** Write all statistics to the log, with log level <b>severity</b>. Called
  311. * in response to a SIGUSR1. */
  312. static void
  313. dumpstats(int severity)
  314. {
  315. time_t now = time(NULL);
  316. time_t elapsed;
  317. size_t rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
  318. tor_log(severity, LD_GENERAL, "Dumping stats:");
  319. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  320. int i = conn_sl_idx;
  321. tor_log(severity, LD_GENERAL,
  322. "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  323. i, (int)conn->s, conn->type, conn_type_to_string(conn->type),
  324. conn->state, conn_state_to_string(conn->type, conn->state),
  325. (int)(now - conn->timestamp_created));
  326. if (!connection_is_listener(conn)) {
  327. tor_log(severity,LD_GENERAL,
  328. "Conn %d is to %s:%d.", i,
  329. safe_str_client(conn->address),
  330. conn->port);
  331. tor_log(severity,LD_GENERAL,
  332. "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
  333. i,
  334. (int)connection_get_inbuf_len(conn),
  335. (int)buf_allocation(conn->inbuf),
  336. (int)(now - conn->timestamp_last_read_allowed));
  337. tor_log(severity,LD_GENERAL,
  338. "Conn %d: %d bytes waiting on outbuf "
  339. "(len %d, last written %d secs ago)",i,
  340. (int)connection_get_outbuf_len(conn),
  341. (int)buf_allocation(conn->outbuf),
  342. (int)(now - conn->timestamp_last_write_allowed));
  343. if (conn->type == CONN_TYPE_OR) {
  344. or_connection_t *or_conn = TO_OR_CONN(conn);
  345. if (or_conn->tls) {
  346. if (tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
  347. &wbuf_cap, &wbuf_len) == 0) {
  348. tor_log(severity, LD_GENERAL,
  349. "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
  350. "%d/%d bytes used on write buffer.",
  351. i, (int)rbuf_len, (int)rbuf_cap, (int)wbuf_len, (int)wbuf_cap);
  352. }
  353. }
  354. }
  355. }
  356. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
  357. * using this conn */
  358. } SMARTLIST_FOREACH_END(conn);
  359. channel_dumpstats(severity);
  360. channel_listener_dumpstats(severity);
  361. tor_log(severity, LD_NET,
  362. "Cells processed: %"PRIu64" padding\n"
  363. " %"PRIu64" create\n"
  364. " %"PRIu64" created\n"
  365. " %"PRIu64" relay\n"
  366. " (%"PRIu64" relayed)\n"
  367. " (%"PRIu64" delivered)\n"
  368. " %"PRIu64" destroy",
  369. (stats_n_padding_cells_processed),
  370. (stats_n_create_cells_processed),
  371. (stats_n_created_cells_processed),
  372. (stats_n_relay_cells_processed),
  373. (stats_n_relay_cells_relayed),
  374. (stats_n_relay_cells_delivered),
  375. (stats_n_destroy_cells_processed));
  376. if (stats_n_data_cells_packaged)
  377. tor_log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
  378. 100*(((double)stats_n_data_bytes_packaged) /
  379. ((double)stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  380. if (stats_n_data_cells_received)
  381. tor_log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
  382. 100*(((double)stats_n_data_bytes_received) /
  383. ((double)stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  384. cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_TAP, "TAP");
  385. cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_NTOR,"ntor");
  386. if (now - time_of_process_start >= 0)
  387. elapsed = now - time_of_process_start;
  388. else
  389. elapsed = 0;
  390. if (elapsed) {
  391. tor_log(severity, LD_NET,
  392. "Average bandwidth: %"PRIu64"/%d = %d bytes/sec reading",
  393. (get_bytes_read()),
  394. (int)elapsed,
  395. (int) (get_bytes_read()/elapsed));
  396. tor_log(severity, LD_NET,
  397. "Average bandwidth: %"PRIu64"/%d = %d bytes/sec writing",
  398. (get_bytes_written()),
  399. (int)elapsed,
  400. (int) (get_bytes_written()/elapsed));
  401. }
  402. tor_log(severity, LD_NET, "--------------- Dumping memory information:");
  403. dumpmemusage(severity);
  404. rep_hist_dump_stats(now,severity);
  405. rend_service_dump_stats(severity);
  406. }
  407. #ifdef _WIN32
  408. #define UNIX_ONLY 0
  409. #else
  410. #define UNIX_ONLY 1
  411. #endif
  412. static struct {
  413. /** A numeric code for this signal. Must match the signal value if
  414. * try_to_register is true. */
  415. int signal_value;
  416. /** True if we should try to register this signal with libevent and catch
  417. * corresponding posix signals. False otherwise. */
  418. int try_to_register;
  419. /** Pointer to hold the event object constructed for this signal. */
  420. struct event *signal_event;
  421. } signal_handlers[] = {
  422. #ifdef SIGINT
  423. { SIGINT, UNIX_ONLY, NULL }, /* do a controlled slow shutdown */
  424. #endif
  425. #ifdef SIGTERM
  426. { SIGTERM, UNIX_ONLY, NULL }, /* to terminate now */
  427. #endif
  428. #ifdef SIGPIPE
  429. { SIGPIPE, UNIX_ONLY, NULL }, /* otherwise SIGPIPE kills us */
  430. #endif
  431. #ifdef SIGUSR1
  432. { SIGUSR1, UNIX_ONLY, NULL }, /* dump stats */
  433. #endif
  434. #ifdef SIGUSR2
  435. { SIGUSR2, UNIX_ONLY, NULL }, /* go to loglevel debug */
  436. #endif
  437. #ifdef SIGHUP
  438. { SIGHUP, UNIX_ONLY, NULL }, /* to reload config, retry conns, etc */
  439. #endif
  440. #ifdef SIGXFSZ
  441. { SIGXFSZ, UNIX_ONLY, NULL }, /* handle file-too-big resource exhaustion */
  442. #endif
  443. #ifdef SIGCHLD
  444. { SIGCHLD, UNIX_ONLY, NULL }, /* handle dns/cpu workers that exit */
  445. #endif
  446. /* These are controller-only */
  447. { SIGNEWNYM, 0, NULL },
  448. { SIGCLEARDNSCACHE, 0, NULL },
  449. { SIGHEARTBEAT, 0, NULL },
  450. { SIGACTIVE, 0, NULL },
  451. { SIGDORMANT, 0, NULL },
  452. { -1, -1, NULL }
  453. };
  454. /** Set up the signal handler events for this process, and register them
  455. * with libevent if appropriate. */
  456. void
  457. handle_signals(void)
  458. {
  459. int i;
  460. const int enabled = !get_options()->DisableSignalHandlers;
  461. for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
  462. /* Signal handlers are only registered with libevent if they need to catch
  463. * real POSIX signals. We construct these signal handler events in either
  464. * case, though, so that controllers can activate them with the SIGNAL
  465. * command.
  466. */
  467. if (enabled && signal_handlers[i].try_to_register) {
  468. signal_handlers[i].signal_event =
  469. tor_evsignal_new(tor_libevent_get_base(),
  470. signal_handlers[i].signal_value,
  471. signal_callback,
  472. &signal_handlers[i].signal_value);
  473. if (event_add(signal_handlers[i].signal_event, NULL))
  474. log_warn(LD_BUG, "Error from libevent when adding "
  475. "event for signal %d",
  476. signal_handlers[i].signal_value);
  477. } else {
  478. signal_handlers[i].signal_event =
  479. tor_event_new(tor_libevent_get_base(), -1,
  480. EV_SIGNAL, signal_callback,
  481. &signal_handlers[i].signal_value);
  482. }
  483. }
  484. }
  485. /* Cause the signal handler for signal_num to be called in the event loop. */
  486. void
  487. activate_signal(int signal_num)
  488. {
  489. int i;
  490. for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
  491. if (signal_handlers[i].signal_value == signal_num) {
  492. event_active(signal_handlers[i].signal_event, EV_SIGNAL, 1);
  493. return;
  494. }
  495. }
  496. }
  497. /** Main entry point for the Tor command-line client. Return 0 on "success",
  498. * negative on "failure", and positive on "success and exit".
  499. */
  500. int
  501. tor_init(int argc, char *argv[])
  502. {
  503. char progname[256];
  504. int quiet = 0;
  505. time_of_process_start = time(NULL);
  506. tor_init_connection_lists();
  507. /* Have the log set up with our application name. */
  508. tor_snprintf(progname, sizeof(progname), "Tor %s", get_version());
  509. log_set_application_name(progname);
  510. /* Initialize the history structures. */
  511. rep_hist_init();
  512. /* Initialize the service cache. */
  513. rend_cache_init();
  514. addressmap_init(); /* Init the client dns cache. Do it always, since it's
  515. * cheap. */
  516. /* Initialize the HS subsystem. */
  517. hs_init();
  518. {
  519. /* We search for the "quiet" option first, since it decides whether we
  520. * will log anything at all to the command line. */
  521. config_line_t *opts = NULL, *cmdline_opts = NULL;
  522. const config_line_t *cl;
  523. (void) config_parse_commandline(argc, argv, 1, &opts, &cmdline_opts);
  524. for (cl = cmdline_opts; cl; cl = cl->next) {
  525. if (!strcmp(cl->key, "--hush"))
  526. quiet = 1;
  527. if (!strcmp(cl->key, "--quiet") ||
  528. !strcmp(cl->key, "--dump-config"))
  529. quiet = 2;
  530. /* The following options imply --hush */
  531. if (!strcmp(cl->key, "--version") || !strcmp(cl->key, "--digests") ||
  532. !strcmp(cl->key, "--list-torrc-options") ||
  533. !strcmp(cl->key, "--library-versions") ||
  534. !strcmp(cl->key, "--hash-password") ||
  535. !strcmp(cl->key, "-h") || !strcmp(cl->key, "--help")) {
  536. if (quiet < 1)
  537. quiet = 1;
  538. }
  539. }
  540. config_free_lines(opts);
  541. config_free_lines(cmdline_opts);
  542. }
  543. /* give it somewhere to log to initially */
  544. switch (quiet) {
  545. case 2:
  546. /* no initial logging */
  547. break;
  548. case 1:
  549. add_temp_log(LOG_WARN);
  550. break;
  551. default:
  552. add_temp_log(LOG_NOTICE);
  553. }
  554. quiet_level = quiet;
  555. {
  556. const char *version = get_version();
  557. log_notice(LD_GENERAL, "Tor %s running on %s with Libevent %s, "
  558. "%s %s, Zlib %s, Liblzma %s, and Libzstd %s.", version,
  559. get_uname(),
  560. tor_libevent_get_version_str(),
  561. crypto_get_library_name(),
  562. crypto_get_library_version_string(),
  563. tor_compress_supports_method(ZLIB_METHOD) ?
  564. tor_compress_version_str(ZLIB_METHOD) : "N/A",
  565. tor_compress_supports_method(LZMA_METHOD) ?
  566. tor_compress_version_str(LZMA_METHOD) : "N/A",
  567. tor_compress_supports_method(ZSTD_METHOD) ?
  568. tor_compress_version_str(ZSTD_METHOD) : "N/A");
  569. log_notice(LD_GENERAL, "Tor can't help you if you use it wrong! "
  570. "Learn how to be safe at "
  571. "https://www.torproject.org/download/download#warning");
  572. if (strstr(version, "alpha") || strstr(version, "beta"))
  573. log_notice(LD_GENERAL, "This version is not a stable Tor release. "
  574. "Expect more bugs than usual.");
  575. tor_compress_log_init_warnings();
  576. }
  577. #ifdef HAVE_RUST
  578. rust_log_welcome_string();
  579. #endif /* defined(HAVE_RUST) */
  580. int init_rv = options_init_from_torrc(argc,argv);
  581. if (init_rv < 0) {
  582. log_err(LD_CONFIG,"Reading config failed--see warnings above.");
  583. return -1;
  584. } else if (init_rv > 0) {
  585. // We succeeded, and should exit anyway -- probably the user just said
  586. // "--version" or something like that.
  587. return 1;
  588. }
  589. /* The options are now initialised */
  590. const or_options_t *options = get_options();
  591. /* Initialize channelpadding and circpad parameters to defaults
  592. * until we get a consensus */
  593. channelpadding_new_consensus_params(NULL);
  594. circpad_new_consensus_params(NULL);
  595. /* Initialize circuit padding to defaults+torrc until we get a consensus */
  596. circpad_machines_init();
  597. /* Initialize predicted ports list after loading options */
  598. predicted_ports_init();
  599. #ifndef _WIN32
  600. if (geteuid()==0)
  601. log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
  602. "and you probably shouldn't.");
  603. #endif
  604. if (crypto_global_init(options->HardwareAccel,
  605. options->AccelName,
  606. options->AccelDir)) {
  607. log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
  608. return -1;
  609. }
  610. if (tor_init_libevent_rng() < 0) {
  611. log_warn(LD_NET, "Problem initializing libevent RNG.");
  612. }
  613. /* Scan/clean unparseable descriptors; after reading config */
  614. routerparse_init();
  615. return 0;
  616. }
  617. /** A lockfile structure, used to prevent two Tors from messing with the
  618. * data directory at once. If this variable is non-NULL, we're holding
  619. * the lockfile. */
  620. static tor_lockfile_t *lockfile = NULL;
  621. /** Try to grab the lock file described in <b>options</b>, if we do not
  622. * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
  623. * holding the lock, and exit if we can't get it after waiting. Otherwise,
  624. * return -1 if we can't get the lockfile. Return 0 on success.
  625. */
  626. int
  627. try_locking(const or_options_t *options, int err_if_locked)
  628. {
  629. if (lockfile)
  630. return 0;
  631. else {
  632. char *fname = options_get_datadir_fname(options, "lock");
  633. int already_locked = 0;
  634. tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
  635. tor_free(fname);
  636. if (!lf) {
  637. if (err_if_locked && already_locked) {
  638. int r;
  639. log_warn(LD_GENERAL, "It looks like another Tor process is running "
  640. "with the same data directory. Waiting 5 seconds to see "
  641. "if it goes away.");
  642. #ifndef _WIN32
  643. sleep(5);
  644. #else
  645. Sleep(5000);
  646. #endif
  647. r = try_locking(options, 0);
  648. if (r<0) {
  649. log_err(LD_GENERAL, "No, it's still there. Exiting.");
  650. return -1;
  651. }
  652. return r;
  653. }
  654. return -1;
  655. }
  656. lockfile = lf;
  657. return 0;
  658. }
  659. }
  660. /** Return true iff we've successfully acquired the lock file. */
  661. int
  662. have_lockfile(void)
  663. {
  664. return lockfile != NULL;
  665. }
  666. /** If we have successfully acquired the lock file, release it. */
  667. void
  668. release_lockfile(void)
  669. {
  670. if (lockfile) {
  671. tor_lockfile_unlock(lockfile);
  672. lockfile = NULL;
  673. }
  674. }
  675. /** Free all memory that we might have allocated somewhere.
  676. * If <b>postfork</b>, we are a worker process and we want to free
  677. * only the parts of memory that we won't touch. If !<b>postfork</b>,
  678. * Tor is shutting down and we should free everything.
  679. *
  680. * Helps us find the real leaks with sanitizers and the like. Also valgrind
  681. * should then report 0 reachable in its leak report (in an ideal world --
  682. * in practice libevent, SSL, libc etc never quite free everything). */
  683. void
  684. tor_free_all(int postfork)
  685. {
  686. if (!postfork) {
  687. evdns_shutdown(1);
  688. }
  689. geoip_free_all();
  690. geoip_stats_free_all();
  691. dirvote_free_all();
  692. routerlist_free_all();
  693. networkstatus_free_all();
  694. addressmap_free_all();
  695. dirserv_free_fingerprint_list();
  696. dirserv_free_all();
  697. dirserv_clear_measured_bw_cache();
  698. rend_cache_free_all();
  699. rend_service_authorization_free_all();
  700. rep_hist_free_all();
  701. dns_free_all();
  702. clear_pending_onions();
  703. circuit_free_all();
  704. circpad_machines_free();
  705. entry_guards_free_all();
  706. pt_free_all();
  707. channel_tls_free_all();
  708. channel_free_all();
  709. connection_free_all();
  710. connection_edge_free_all();
  711. scheduler_free_all();
  712. nodelist_free_all();
  713. microdesc_free_all();
  714. routerparse_free_all();
  715. ext_orport_free_all();
  716. control_free_all();
  717. protover_free_all();
  718. bridges_free_all();
  719. consdiffmgr_free_all();
  720. hs_free_all();
  721. dos_free_all();
  722. circuitmux_ewma_free_all();
  723. accounting_free_all();
  724. protover_summary_cache_free_all();
  725. if (!postfork) {
  726. config_free_all();
  727. or_state_free_all();
  728. router_free_all();
  729. routerkeys_free_all();
  730. policies_free_all();
  731. }
  732. if (!postfork) {
  733. #ifndef _WIN32
  734. tor_getpwnam(NULL);
  735. #endif
  736. }
  737. /* stuff in main.c */
  738. tor_mainloop_free_all();
  739. if (!postfork) {
  740. release_lockfile();
  741. }
  742. tor_libevent_free_all();
  743. subsystems_shutdown();
  744. /* Stuff in util.c and address.c*/
  745. if (!postfork) {
  746. esc_router_info(NULL);
  747. }
  748. }
  749. /**
  750. * Remove the specified file, and log a warning if the operation fails for
  751. * any reason other than the file not existing. Ignores NULL filenames.
  752. */
  753. void
  754. tor_remove_file(const char *filename)
  755. {
  756. if (filename && tor_unlink(filename) != 0 && errno != ENOENT) {
  757. log_warn(LD_FS, "Couldn't unlink %s: %s",
  758. filename, strerror(errno));
  759. }
  760. }
  761. /** Do whatever cleanup is necessary before shutting Tor down. */
  762. void
  763. tor_cleanup(void)
  764. {
  765. const or_options_t *options = get_options();
  766. if (options->command == CMD_RUN_TOR) {
  767. time_t now = time(NULL);
  768. /* Remove our pid file. We don't care if there was an error when we
  769. * unlink, nothing we could do about it anyways. */
  770. tor_remove_file(options->PidFile);
  771. /* Remove control port file */
  772. tor_remove_file(options->ControlPortWriteToFile);
  773. /* Remove cookie authentication file */
  774. {
  775. char *cookie_fname = get_controller_cookie_file_name();
  776. tor_remove_file(cookie_fname);
  777. tor_free(cookie_fname);
  778. }
  779. /* Remove Extended ORPort cookie authentication file */
  780. {
  781. char *cookie_fname = get_ext_or_auth_cookie_file_name();
  782. tor_remove_file(cookie_fname);
  783. tor_free(cookie_fname);
  784. }
  785. if (accounting_is_enabled(options))
  786. accounting_record_bandwidth_usage(now, get_or_state());
  787. or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
  788. or_state_save(now);
  789. if (authdir_mode(options)) {
  790. sr_save_and_cleanup();
  791. }
  792. if (authdir_mode_tests_reachability(options))
  793. rep_hist_record_mtbf_data(now, 0);
  794. keypin_close_journal();
  795. }
  796. timers_shutdown();
  797. tor_free_all(0); /* We could move tor_free_all back into the ifdef below
  798. later, if it makes shutdown unacceptably slow. But for
  799. now, leave it here: it's helped us catch bugs in the
  800. past. */
  801. }
  802. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  803. static int
  804. do_list_fingerprint(void)
  805. {
  806. char buf[FINGERPRINT_LEN+1];
  807. crypto_pk_t *k;
  808. const char *nickname = get_options()->Nickname;
  809. sandbox_disable_getaddrinfo_cache();
  810. if (!server_mode(get_options())) {
  811. log_err(LD_GENERAL,
  812. "Clients don't have long-term identity keys. Exiting.");
  813. return -1;
  814. }
  815. tor_assert(nickname);
  816. if (init_keys() < 0) {
  817. log_err(LD_GENERAL,"Error initializing keys; exiting.");
  818. return -1;
  819. }
  820. if (!(k = get_server_identity_key())) {
  821. log_err(LD_GENERAL,"Error: missing identity key.");
  822. return -1;
  823. }
  824. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  825. log_err(LD_BUG, "Error computing fingerprint");
  826. return -1;
  827. }
  828. printf("%s %s\n", nickname, buf);
  829. return 0;
  830. }
  831. /** Entry point for password hashing: take the desired password from
  832. * the command line, and print its salted hash to stdout. **/
  833. static void
  834. do_hash_password(void)
  835. {
  836. char output[256];
  837. char key[S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN];
  838. crypto_rand(key, S2K_RFC2440_SPECIFIER_LEN-1);
  839. key[S2K_RFC2440_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  840. secret_to_key_rfc2440(key+S2K_RFC2440_SPECIFIER_LEN, DIGEST_LEN,
  841. get_options()->command_arg, strlen(get_options()->command_arg),
  842. key);
  843. base16_encode(output, sizeof(output), key, sizeof(key));
  844. printf("16:%s\n",output);
  845. }
  846. /** Entry point for configuration dumping: write the configuration to
  847. * stdout. */
  848. static int
  849. do_dump_config(void)
  850. {
  851. const or_options_t *options = get_options();
  852. const char *arg = options->command_arg;
  853. int how;
  854. char *opts;
  855. if (!strcmp(arg, "short")) {
  856. how = OPTIONS_DUMP_MINIMAL;
  857. } else if (!strcmp(arg, "non-builtin")) {
  858. how = OPTIONS_DUMP_DEFAULTS;
  859. } else if (!strcmp(arg, "full")) {
  860. how = OPTIONS_DUMP_ALL;
  861. } else {
  862. fprintf(stderr, "No valid argument to --dump-config found!\n");
  863. fprintf(stderr, "Please select 'short', 'non-builtin', or 'full'.\n");
  864. return -1;
  865. }
  866. opts = options_dump(options, how);
  867. printf("%s", opts);
  868. tor_free(opts);
  869. return 0;
  870. }
  871. static void
  872. init_addrinfo(void)
  873. {
  874. if (! server_mode(get_options()) ||
  875. (get_options()->Address && strlen(get_options()->Address) > 0)) {
  876. /* We don't need to seed our own hostname, because we won't be calling
  877. * resolve_my_address on it.
  878. */
  879. return;
  880. }
  881. char hname[256];
  882. // host name to sandbox
  883. gethostname(hname, sizeof(hname));
  884. tor_add_addrinfo(hname);
  885. }
  886. static sandbox_cfg_t*
  887. sandbox_init_filter(void)
  888. {
  889. const or_options_t *options = get_options();
  890. sandbox_cfg_t *cfg = sandbox_cfg_new();
  891. int i;
  892. sandbox_cfg_allow_openat_filename(&cfg,
  893. get_cachedir_fname("cached-status"));
  894. #define OPEN(name) \
  895. sandbox_cfg_allow_open_filename(&cfg, tor_strdup(name))
  896. #define OPEN_DATADIR(name) \
  897. sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname(name))
  898. #define OPEN_DATADIR2(name, name2) \
  899. sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname2((name), (name2)))
  900. #define OPEN_DATADIR_SUFFIX(name, suffix) do { \
  901. OPEN_DATADIR(name); \
  902. OPEN_DATADIR(name suffix); \
  903. } while (0)
  904. #define OPEN_DATADIR2_SUFFIX(name, name2, suffix) do { \
  905. OPEN_DATADIR2(name, name2); \
  906. OPEN_DATADIR2(name, name2 suffix); \
  907. } while (0)
  908. #define OPEN_KEY_DIRECTORY() \
  909. sandbox_cfg_allow_open_filename(&cfg, tor_strdup(options->KeyDirectory))
  910. #define OPEN_CACHEDIR(name) \
  911. sandbox_cfg_allow_open_filename(&cfg, get_cachedir_fname(name))
  912. #define OPEN_CACHEDIR_SUFFIX(name, suffix) do { \
  913. OPEN_CACHEDIR(name); \
  914. OPEN_CACHEDIR(name suffix); \
  915. } while (0)
  916. #define OPEN_KEYDIR(name) \
  917. sandbox_cfg_allow_open_filename(&cfg, get_keydir_fname(name))
  918. #define OPEN_KEYDIR_SUFFIX(name, suffix) do { \
  919. OPEN_KEYDIR(name); \
  920. OPEN_KEYDIR(name suffix); \
  921. } while (0)
  922. OPEN(options->DataDirectory);
  923. OPEN_KEY_DIRECTORY();
  924. OPEN_CACHEDIR_SUFFIX("cached-certs", ".tmp");
  925. OPEN_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
  926. OPEN_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
  927. OPEN_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
  928. OPEN_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
  929. OPEN_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
  930. OPEN_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
  931. OPEN_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
  932. OPEN_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
  933. OPEN_CACHEDIR("cached-descriptors.tmp.tmp");
  934. OPEN_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
  935. OPEN_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
  936. OPEN_CACHEDIR("cached-extrainfo.tmp.tmp");
  937. OPEN_DATADIR_SUFFIX("state", ".tmp");
  938. OPEN_DATADIR_SUFFIX("sr-state", ".tmp");
  939. OPEN_DATADIR_SUFFIX("unparseable-desc", ".tmp");
  940. OPEN_DATADIR_SUFFIX("v3-status-votes", ".tmp");
  941. OPEN_DATADIR("key-pinning-journal");
  942. OPEN("/dev/srandom");
  943. OPEN("/dev/urandom");
  944. OPEN("/dev/random");
  945. OPEN("/etc/hosts");
  946. OPEN("/proc/meminfo");
  947. if (options->BridgeAuthoritativeDir)
  948. OPEN_DATADIR_SUFFIX("networkstatus-bridges", ".tmp");
  949. if (authdir_mode(options))
  950. OPEN_DATADIR("approved-routers");
  951. if (options->ServerDNSResolvConfFile)
  952. sandbox_cfg_allow_open_filename(&cfg,
  953. tor_strdup(options->ServerDNSResolvConfFile));
  954. else
  955. sandbox_cfg_allow_open_filename(&cfg, tor_strdup("/etc/resolv.conf"));
  956. for (i = 0; i < 2; ++i) {
  957. if (get_torrc_fname(i)) {
  958. sandbox_cfg_allow_open_filename(&cfg, tor_strdup(get_torrc_fname(i)));
  959. }
  960. }
  961. SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, {
  962. OPEN(f);
  963. });
  964. #define RENAME_SUFFIX(name, suffix) \
  965. sandbox_cfg_allow_rename(&cfg, \
  966. get_datadir_fname(name suffix), \
  967. get_datadir_fname(name))
  968. #define RENAME_SUFFIX2(prefix, name, suffix) \
  969. sandbox_cfg_allow_rename(&cfg, \
  970. get_datadir_fname2(prefix, name suffix), \
  971. get_datadir_fname2(prefix, name))
  972. #define RENAME_CACHEDIR_SUFFIX(name, suffix) \
  973. sandbox_cfg_allow_rename(&cfg, \
  974. get_cachedir_fname(name suffix), \
  975. get_cachedir_fname(name))
  976. #define RENAME_KEYDIR_SUFFIX(name, suffix) \
  977. sandbox_cfg_allow_rename(&cfg, \
  978. get_keydir_fname(name suffix), \
  979. get_keydir_fname(name))
  980. RENAME_CACHEDIR_SUFFIX("cached-certs", ".tmp");
  981. RENAME_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
  982. RENAME_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
  983. RENAME_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
  984. RENAME_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
  985. RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
  986. RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".new");
  987. RENAME_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
  988. RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
  989. RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".new");
  990. RENAME_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
  991. RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
  992. RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".new");
  993. RENAME_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
  994. RENAME_SUFFIX("state", ".tmp");
  995. RENAME_SUFFIX("sr-state", ".tmp");
  996. RENAME_SUFFIX("unparseable-desc", ".tmp");
  997. RENAME_SUFFIX("v3-status-votes", ".tmp");
  998. if (options->BridgeAuthoritativeDir)
  999. RENAME_SUFFIX("networkstatus-bridges", ".tmp");
  1000. #define STAT_DATADIR(name) \
  1001. sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname(name))
  1002. #define STAT_CACHEDIR(name) \
  1003. sandbox_cfg_allow_stat_filename(&cfg, get_cachedir_fname(name))
  1004. #define STAT_DATADIR2(name, name2) \
  1005. sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname2((name), (name2)))
  1006. #define STAT_KEY_DIRECTORY() \
  1007. sandbox_cfg_allow_stat_filename(&cfg, tor_strdup(options->KeyDirectory))
  1008. STAT_DATADIR(NULL);
  1009. STAT_DATADIR("lock");
  1010. STAT_DATADIR("state");
  1011. STAT_DATADIR("router-stability");
  1012. STAT_CACHEDIR("cached-extrainfo.new");
  1013. {
  1014. smartlist_t *files = smartlist_new();
  1015. tor_log_get_logfile_names(files);
  1016. SMARTLIST_FOREACH(files, char *, file_name, {
  1017. /* steals reference */
  1018. sandbox_cfg_allow_open_filename(&cfg, file_name);
  1019. });
  1020. smartlist_free(files);
  1021. }
  1022. {
  1023. smartlist_t *files = smartlist_new();
  1024. smartlist_t *dirs = smartlist_new();
  1025. hs_service_lists_fnames_for_sandbox(files, dirs);
  1026. SMARTLIST_FOREACH(files, char *, file_name, {
  1027. char *tmp_name = NULL;
  1028. tor_asprintf(&tmp_name, "%s.tmp", file_name);
  1029. sandbox_cfg_allow_rename(&cfg,
  1030. tor_strdup(tmp_name), tor_strdup(file_name));
  1031. /* steals references */
  1032. sandbox_cfg_allow_open_filename(&cfg, file_name);
  1033. sandbox_cfg_allow_open_filename(&cfg, tmp_name);
  1034. });
  1035. SMARTLIST_FOREACH(dirs, char *, dir, {
  1036. /* steals reference */
  1037. sandbox_cfg_allow_stat_filename(&cfg, dir);
  1038. });
  1039. smartlist_free(files);
  1040. smartlist_free(dirs);
  1041. }
  1042. {
  1043. char *fname;
  1044. if ((fname = get_controller_cookie_file_name())) {
  1045. sandbox_cfg_allow_open_filename(&cfg, fname);
  1046. }
  1047. if ((fname = get_ext_or_auth_cookie_file_name())) {
  1048. sandbox_cfg_allow_open_filename(&cfg, fname);
  1049. }
  1050. }
  1051. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), port_cfg_t *, port) {
  1052. if (!port->is_unix_addr)
  1053. continue;
  1054. /* When we open an AF_UNIX address, we want permission to open the
  1055. * directory that holds it. */
  1056. char *dirname = tor_strdup(port->unix_addr);
  1057. if (get_parent_directory(dirname) == 0) {
  1058. OPEN(dirname);
  1059. }
  1060. tor_free(dirname);
  1061. sandbox_cfg_allow_chmod_filename(&cfg, tor_strdup(port->unix_addr));
  1062. sandbox_cfg_allow_chown_filename(&cfg, tor_strdup(port->unix_addr));
  1063. } SMARTLIST_FOREACH_END(port);
  1064. if (options->DirPortFrontPage) {
  1065. sandbox_cfg_allow_open_filename(&cfg,
  1066. tor_strdup(options->DirPortFrontPage));
  1067. }
  1068. // orport
  1069. if (server_mode(get_options())) {
  1070. OPEN_KEYDIR_SUFFIX("secret_id_key", ".tmp");
  1071. OPEN_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
  1072. OPEN_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
  1073. OPEN_KEYDIR("secret_id_key.old");
  1074. OPEN_KEYDIR("secret_onion_key.old");
  1075. OPEN_KEYDIR("secret_onion_key_ntor.old");
  1076. OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key", ".tmp");
  1077. OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key_encrypted", ".tmp");
  1078. OPEN_KEYDIR_SUFFIX("ed25519_master_id_public_key", ".tmp");
  1079. OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key", ".tmp");
  1080. OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key_encrypted", ".tmp");
  1081. OPEN_KEYDIR_SUFFIX("ed25519_signing_public_key", ".tmp");
  1082. OPEN_KEYDIR_SUFFIX("ed25519_signing_cert", ".tmp");
  1083. OPEN_DATADIR2_SUFFIX("stats", "bridge-stats", ".tmp");
  1084. OPEN_DATADIR2_SUFFIX("stats", "dirreq-stats", ".tmp");
  1085. OPEN_DATADIR2_SUFFIX("stats", "entry-stats", ".tmp");
  1086. OPEN_DATADIR2_SUFFIX("stats", "exit-stats", ".tmp");
  1087. OPEN_DATADIR2_SUFFIX("stats", "buffer-stats", ".tmp");
  1088. OPEN_DATADIR2_SUFFIX("stats", "conn-stats", ".tmp");
  1089. OPEN_DATADIR2_SUFFIX("stats", "hidserv-stats", ".tmp");
  1090. OPEN_DATADIR("approved-routers");
  1091. OPEN_DATADIR_SUFFIX("fingerprint", ".tmp");
  1092. OPEN_DATADIR_SUFFIX("hashed-fingerprint", ".tmp");
  1093. OPEN_DATADIR_SUFFIX("router-stability", ".tmp");
  1094. OPEN("/etc/resolv.conf");
  1095. RENAME_SUFFIX("fingerprint", ".tmp");
  1096. RENAME_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
  1097. RENAME_KEYDIR_SUFFIX("secret_id_key", ".tmp");
  1098. RENAME_KEYDIR_SUFFIX("secret_id_key.old", ".tmp");
  1099. RENAME_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
  1100. RENAME_KEYDIR_SUFFIX("secret_onion_key.old", ".tmp");
  1101. RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
  1102. RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
  1103. RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
  1104. RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
  1105. RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
  1106. RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
  1107. RENAME_SUFFIX2("stats", "hidserv-stats", ".tmp");
  1108. RENAME_SUFFIX("hashed-fingerprint", ".tmp");
  1109. RENAME_SUFFIX("router-stability", ".tmp");
  1110. RENAME_KEYDIR_SUFFIX("ed25519_master_id_secret_key", ".tmp");
  1111. RENAME_KEYDIR_SUFFIX("ed25519_master_id_secret_key_encrypted", ".tmp");
  1112. RENAME_KEYDIR_SUFFIX("ed25519_master_id_public_key", ".tmp");
  1113. RENAME_KEYDIR_SUFFIX("ed25519_signing_secret_key", ".tmp");
  1114. RENAME_KEYDIR_SUFFIX("ed25519_signing_cert", ".tmp");
  1115. sandbox_cfg_allow_rename(&cfg,
  1116. get_keydir_fname("secret_onion_key"),
  1117. get_keydir_fname("secret_onion_key.old"));
  1118. sandbox_cfg_allow_rename(&cfg,
  1119. get_keydir_fname("secret_onion_key_ntor"),
  1120. get_keydir_fname("secret_onion_key_ntor.old"));
  1121. STAT_KEY_DIRECTORY();
  1122. OPEN_DATADIR("stats");
  1123. STAT_DATADIR("stats");
  1124. STAT_DATADIR2("stats", "dirreq-stats");
  1125. consdiffmgr_register_with_sandbox(&cfg);
  1126. }
  1127. init_addrinfo();
  1128. return cfg;
  1129. }
  1130. int
  1131. run_tor_main_loop(void)
  1132. {
  1133. handle_signals();
  1134. timers_initialize();
  1135. initialize_mainloop_events();
  1136. /* load the private keys, if we're supposed to have them, and set up the
  1137. * TLS context. */
  1138. if (! client_identity_key_is_set()) {
  1139. if (init_keys() < 0) {
  1140. log_err(LD_OR, "Error initializing keys; exiting");
  1141. return -1;
  1142. }
  1143. }
  1144. /* Set up our buckets */
  1145. connection_bucket_init();
  1146. /* initialize the bootstrap status events to know we're starting up */
  1147. control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
  1148. /* Initialize the keypinning log. */
  1149. if (authdir_mode_v3(get_options())) {
  1150. char *fname = get_datadir_fname("key-pinning-journal");
  1151. int r = 0;
  1152. if (keypin_load_journal(fname)<0) {
  1153. log_err(LD_DIR, "Error loading key-pinning journal: %s",strerror(errno));
  1154. r = -1;
  1155. }
  1156. if (keypin_open_journal(fname)<0) {
  1157. log_err(LD_DIR, "Error opening key-pinning journal: %s",strerror(errno));
  1158. r = -1;
  1159. }
  1160. tor_free(fname);
  1161. if (r)
  1162. return r;
  1163. }
  1164. {
  1165. /* This is the old name for key-pinning-journal. These got corrupted
  1166. * in a couple of cases by #16530, so we started over. See #16580 for
  1167. * the rationale and for other options we didn't take. We can remove
  1168. * this code once all the authorities that ran 0.2.7.1-alpha-dev are
  1169. * upgraded.
  1170. */
  1171. char *fname = get_datadir_fname("key-pinning-entries");
  1172. unlink(fname);
  1173. tor_free(fname);
  1174. }
  1175. if (trusted_dirs_reload_certs()) {
  1176. log_warn(LD_DIR,
  1177. "Couldn't load all cached v3 certificates. Starting anyway.");
  1178. }
  1179. if (router_reload_consensus_networkstatus()) {
  1180. return -1;
  1181. }
  1182. /* load the routers file, or assign the defaults. */
  1183. if (router_reload_router_list()) {
  1184. return -1;
  1185. }
  1186. /* load the networkstatuses. (This launches a download for new routers as
  1187. * appropriate.)
  1188. */
  1189. const time_t now = time(NULL);
  1190. directory_info_has_arrived(now, 1, 0);
  1191. if (server_mode(get_options()) || dir_server_mode(get_options())) {
  1192. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  1193. cpu_init();
  1194. }
  1195. consdiffmgr_enable_background_compression();
  1196. /* Setup shared random protocol subsystem. */
  1197. if (authdir_mode_v3(get_options())) {
  1198. if (sr_init(1) < 0) {
  1199. return -1;
  1200. }
  1201. }
  1202. /* initialize dns resolve map, spawn workers if needed */
  1203. if (dns_init() < 0) {
  1204. if (get_options()->ServerDNSAllowBrokenConfig)
  1205. log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
  1206. "Network not up yet? Will try again soon.");
  1207. else {
  1208. log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
  1209. "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
  1210. }
  1211. }
  1212. #ifdef HAVE_SYSTEMD
  1213. {
  1214. const int r = sd_notify(0, "READY=1");
  1215. if (r < 0) {
  1216. log_warn(LD_GENERAL, "Unable to send readiness to systemd: %s",
  1217. strerror(r));
  1218. } else if (r > 0) {
  1219. log_notice(LD_GENERAL, "Signaled readiness to systemd");
  1220. } else {
  1221. log_info(LD_GENERAL, "Systemd NOTIFY_SOCKET not present.");
  1222. }
  1223. }
  1224. #endif /* defined(HAVE_SYSTEMD) */
  1225. return do_main_loop();
  1226. }
  1227. /* Main entry point for the Tor process. Called from tor_main(), and by
  1228. * anybody embedding Tor. */
  1229. int
  1230. tor_run_main(const tor_main_configuration_t *tor_cfg)
  1231. {
  1232. int result = 0;
  1233. #ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
  1234. event_set_mem_functions(tor_malloc_, tor_realloc_, tor_free_);
  1235. #endif
  1236. subsystems_init();
  1237. init_protocol_warning_severity_level();
  1238. int argc = tor_cfg->argc + tor_cfg->argc_owned;
  1239. char **argv = tor_calloc(argc, sizeof(char*));
  1240. memcpy(argv, tor_cfg->argv, tor_cfg->argc*sizeof(char*));
  1241. if (tor_cfg->argc_owned)
  1242. memcpy(argv + tor_cfg->argc, tor_cfg->argv_owned,
  1243. tor_cfg->argc_owned*sizeof(char*));
  1244. #ifdef NT_SERVICE
  1245. {
  1246. int done = 0;
  1247. result = nt_service_parse_options(argc, argv, &done);
  1248. if (done) {
  1249. goto done;
  1250. }
  1251. }
  1252. #endif /* defined(NT_SERVICE) */
  1253. {
  1254. int init_rv = tor_init(argc, argv);
  1255. if (init_rv) {
  1256. tor_free_all(0);
  1257. result = (init_rv < 0) ? -1 : 0;
  1258. goto done;
  1259. }
  1260. }
  1261. if (get_options()->Sandbox && get_options()->command == CMD_RUN_TOR) {
  1262. sandbox_cfg_t* cfg = sandbox_init_filter();
  1263. if (sandbox_init(cfg)) {
  1264. tor_free(argv);
  1265. log_err(LD_BUG,"Failed to create syscall sandbox filter");
  1266. tor_free_all(0);
  1267. return -1;
  1268. }
  1269. tor_make_getaddrinfo_cache_active();
  1270. // registering libevent rng
  1271. #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
  1272. evutil_secure_rng_set_urandom_device_file(
  1273. (char*) sandbox_intern_string("/dev/urandom"));
  1274. #endif
  1275. }
  1276. switch (get_options()->command) {
  1277. case CMD_RUN_TOR:
  1278. #ifdef NT_SERVICE
  1279. nt_service_set_state(SERVICE_RUNNING);
  1280. #endif
  1281. result = run_tor_main_loop();
  1282. break;
  1283. case CMD_KEYGEN:
  1284. result = load_ed_keys(get_options(), time(NULL)) < 0;
  1285. break;
  1286. case CMD_KEY_EXPIRATION:
  1287. init_keys();
  1288. result = log_cert_expiration();
  1289. break;
  1290. case CMD_LIST_FINGERPRINT:
  1291. result = do_list_fingerprint();
  1292. break;
  1293. case CMD_HASH_PASSWORD:
  1294. do_hash_password();
  1295. result = 0;
  1296. break;
  1297. case CMD_VERIFY_CONFIG:
  1298. if (quiet_level == 0)
  1299. printf("Configuration was valid\n");
  1300. result = 0;
  1301. break;
  1302. case CMD_DUMP_CONFIG:
  1303. result = do_dump_config();
  1304. break;
  1305. case CMD_RUN_UNITTESTS: /* only set by test.c */
  1306. default:
  1307. log_warn(LD_BUG,"Illegal command number %d: internal error.",
  1308. get_options()->command);
  1309. result = -1;
  1310. }
  1311. tor_cleanup();
  1312. done:
  1313. tor_free(argv);
  1314. return result;
  1315. }