main.c 47 KB

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