main.c 47 KB

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